python keyboard input

How to input python, let's take a look

enter a string

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

Enter 2 numbers to calculate

2 numbers separated by spaces

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

This result is obviously incorrect, because the input a and b are characters and not integers, you can use type() to view the attributes

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

So we have to convert them to integers

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

2 numbers separated by commas

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

enter a number

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

You can see that it is a character and not an integer.
Use the following method

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

The resulting input is an integer

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

The same goes for floating point numbers

multiple number input

>>> 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
>>> 

Guess you like

Origin blog.csdn.net/weixin_46322367/article/details/105544132