python键盘输入

python怎么进行输入呢,下面一起来看看吧

输入一个字符串

>>> str=input("请输入一个字符串:")
请输入一个字符串:i like python
>>> print(str)
i like python
>>> 

输入2个数进行计算

2个数用空格隔开

>>> a,b=input().split(' ')
1 2
>>> a+b
'12'
>>> 

这样结果显然不正确,因为输入的a,b是字符不是整数,可以用type()查看属性

>>> type(a)
<class 'str'>
>>> type(b)
<class 'str'>
>>> 

所以得把它们转换成整型

>>> a,b=input().split(' ')
1 2
>>> a=int(a)
>>> b=int(b)
>>> a+b
3
>>> 

2个数用逗号隔开

>>> a,b=input().split(',')
1,2
>>> a=int(a)
>>> b=int(b)
>>> a+b
3
>>> 

输入一个数

>>> num=input("请输入一个数:")
请输入一个数:5
>>> type(num)
<class 'str'>
>>> 

可以看到它是字符不是整数
采用下面方法

>>> num=eval(input("请输入一个数:"))
请输入一个数:5
>>> type(num)
<class 'int'>
>>> 

这样所得到的输入就是整型了

>>> num=input("请输入一个数:")
请输入一个数:0.66
>>> type(num)
<class 'str'>
>>> num=eval(input("请输入一个数:"))
请输入一个数:0.66
>>> type(num)
<class 'float'>
>>> 

浮点数也是同样操作

多个数输入

>>> a,b,c,d=input().split(',')
1,2,3,4
>>> a=int(a)
>>> b=int(b)
>>> c=int(c)
>>> d=int(d)
>>> a+b+c+d
10
>>> 

猜你喜欢

转载自blog.csdn.net/weixin_46322367/article/details/105544132