python初学者的总结(初学者笔记-第二章)
接受输入接受输入 receiving input,今天小编就来聊一聊关于python初学者的总结?接下来我们就一起去研究一下吧!
python初学者的总结
接受输入
接受输入 receiving input
我们可以通过调用 input() 函数来接收来自用户的输入。
我们想添加一些字符串在终端上打印东西
input("what is your name? ")
input将在终端上打印这个消息,等待用户回答
所以现在我们可以使用变量获取该值并将其储存在内存中
name = input('what is your name? ')
print(‘Hi’ name)
运行它
what is your name? ABC
Hi ABC
问两个问题:他的名字 和他喜欢的颜色 然后 print 出来 像(ABC likes blue)
name = input('what is your name? ')
color = input('what is your favourite colour')
print( name ' likes ' color)
运行
what is your name? ABC
what is your favourite colourred
ABC likes red
类型转换
input() 函数总是以字符串形式返回数据。
所以,我们通过调用内置的 int() 函数将结果转换为整数。
编写一个程序,询问我们出生的那一年,然后计算我们的年龄
错误示范:
birth_year = input('Birth year: ')
age = 2021 - birth_year
print(age)
运行
Birth year: 2003
Traceback (most recent call last):
File "D:\pythonProject\learnpy\1.py", line 2, in <module>
age = 2021 - birth_year
TypeError: unsupported operand type(s) for -: 'int' and 'str'
第二行是错误的
我们还有一些其他功能,用于将值转换为不同类型
int()用于将字符串转换为正数
float()用于将字符串转换为float和带小数点的数字
bool()将字符串转换为布尔值
我们可以将第二行改为
birth_year = input('Birth year: ')
age = 2021 - int(birth_year)
print(age)
运行
Birth year: 2003
18
询问用户体重 将其转化为公斤然后打印出来
pounds_weight = input('weight (pounds)')
kilograms_weight = int(pounds_weight) * 0.45
print(kilograms_weight)
运行
weight (pounds) 115
51.75
免责声明:本文仅代表文章作者的个人观点,与本站无关。其原创性、真实性以及文中陈述文字和内容未经本站证实,对本文以及其中全部或者部分内容文字的真实性、完整性和原创性本站不作任何保证或承诺,请读者仅作参考,并自行核实相关内容。文章投诉邮箱:anhduc.ph@yahoo.com