Python与用户交互
如何交互
我们使用input()方法来与用户交互,但是无论我们输入的值是数字类型、字符串类型、列表类型,input的接收值都是字符串类型。
name = input('请输入你的名字:')
print(type(name))
请输入你的名字:rayn
<class 'str'>
Python2 和Python3 的交互(了解)
Python2中的raw_input()和Python3中的input()是一样的
但是Python2中的input,用户需要知道自己输入的数据是什么数据类型,否则就会报错。python3会自动强制转换。
``>>> age=input(‘请输入你的年龄:‘) ##python2中的input命令
请输入你的年龄:rad
Traceback (most recent call last):
File "", line 1, in
File "", line 1, in
NameError: name ‘rad‘ is not defined
?```python
age=input('请输入你的年龄') ##Python3中的input命令
请输入你的年龄rad
格式化输出(考试必考)
占位符 (%s和%d)%d可以用做int类型
name = 'rayn'
height = 170
age = 20
print('my name is',name,'my height is',height,'my age is',age )
print('my name is %s my height is %s my age is %s'%(name,height,age))
my name is rayn my height is 170 my age is 20
my name is rayn my height is 170 my age is 20
format格式化 (了解)
name = input('name:>>>')
age = input('age:>>>')
height = input('height:>>>')
print('my name is {},my age is {},my height is{}'.format(name,age,height))
name:>>>rayn
age:>>>20
height:>>>180
my name is rayn,my age is 20,my height is180
f-string 格式化 (考试必考)
name = input('name:>>>')
age = input('age:>>>')
height = input('height:>>>')
print(f'my name is{name},my age is {age},my height is {height}')
name:>>>rayn
age:>>>20
height:>>>180
my name israyn,my age is 20,my height is 180
name = input('name:>>>')
age = input('age:>>>')
height = input('height:>>>')
print(f'my name is{name},my age is {int(age)+2},my height is {int(height)+3}') ##可以直接在大括号内进行算术运算
name:>>>rayn
age:>>>20
height:>>>180
my name israyn,my age is 22,my height is 183
print(f'my name is{name},my age is {int(age)+2},my height is {int(height)+3:.2f}') ##:.2f 标识保留2位小数点
my name israyn,my age is 22,my height is 183.00
原文地址:https://www.cnblogs.com/raynduan/p/10900196.html
时间: 2024-11-03 19:54:03