Python输入
时间:2020-02-23 14:42:49 来源:igfitidea点击:
在本教程中,我们将学习最常用的函数input(),我们经常使用该函数从控制台获取用户的键盘输入。
在我们的许多教程中,我们都使用了它,今天,我们将更加紧密地了解python输入函数。
Python input()
Python输入函数存在于pythonbuiltins.py中。
它从标准输入中读取一个字符串,并删除尾随的换行符。
执行input()语句后,程序将暂停,直到用户提供输入并按下Enter键。
" input()"返回作为用户输入的字符串,不带尾随换行符。
Python获取用户输入
让我们看一个使用python输入函数获取用户输入的简单示例。
# taking an input from the keyboard
a = input()
# taking another input from the keyboard
b = input()
c = a + b
print("a + b = %s + %s = %s" % ( a, b, c ))
这将输出:
45 12 a + b = 45 + 12 = 4512
糟糕!输出是什么? 45和12的加法是4512 ??这是因为input()方法会返回键盘输入中给出的String。
要执行我们真正想要的操作,我们必须将其类型转换为整数,如下所示:
c = int(a) + int(b)
现在它将输出:
45 12 a + b = 45 + 12 = 57
因此,在接受输入后,将其按您想要的方式进行投射。
带有String消息的Python输入函数
在上面的示例中,我们没有得到任何提示。
为了向用户提供这些说明,我们可以进行如下输入:
a = input('Please Enter the first number = ')
b = input('Enter the second number = ')
c = int(a) + int(b)
print("Summation of a + b = %s + %s = %s" % ( a, b, c ))
这将输出:
Please Enter the first number = 45 Enter the second number = 12 Summation of a + b = 45 + 12 = 57
另一个简单的Python用户输入示例
下面的示例使用用户名,并找出其中的元音出现次数。
# taking input from prompt
name =input('what is your name? ')
print('Hello %s' % name)
# taking a counter to count the vowels
count = 0
for i in name:
i = i.capitalize()
if i == 'A' or i == 'E' or i == 'I' or i == 'O' or i == 'U':
count = count + 1
print('Your name contains %s vowels' % count)
关于pythoninput函数,我还应该提到的另一件事是,如果用户点击EOF(对于* nix:Ctrl-D,Windows:Ctrl-Z + Return),它将引发错误。
引发的错误是" EOFError"。
在上面的示例中,如果按Ctrl-D,则输出将显示为:
what is your name? ^D
Traceback (most recent call last):
File "D:/T_Code/PythonPackage3/Input.py", line 2, in
name =input('what is your name? ')
EOFError: EOF when reading a line

