用Python输入
在本教程中,我们将学习如何在Python中进行输入。
在Python2中,我们将找到两个不同的函数来接受用户的输入。一个是raw_input另一个是输入。
函数raw_input([promt])用于将字符串作为用户的输入。
函数input([prompt])用于将整数作为用户的输入。
示例
# taking 'string' input
a = raw_input('Enter your name:- ')
# printing the type
print(type(a))
# taking the 'int' input
b = input()# printing the type
print(type(b))输出结果
如果运行上面的代码,则将得到以下结果。
Enter your name:- Nhooo <type 'str'> 5 <type 'int'>
在Python3中,函数raw_input()被删除。现在,我们只有input([prompt])函数从用户那里获取输入。用户输入的任何内容都将是Python中的字符串。
我们必须使用不同的内置函数将其转换为相应的数据类型。让我们看一些例子。
示例
# taking input from the user
a = input('Enter a name:- ')
# printing the data
print(type(a), a)
# asking number from the user
b = input('Enter a number:- ')
# converting the 'string' to 'int'
b = int(b)
# printing the data
print(type(b), b)输出结果
如果运行上面的代码,则将得到以下结果。
Enter a name:- Nhooo <class 'str'> Nhooo Enter a number:- 5 <class 'int'> 5
结论
如果您对本教程有任何疑问,请在评论部分中提及。