在本教程中,我们将学习最常见的函数input()
that we use frequently to take keyboard input from the user from the console. In our many tutorial we have used this, today we will see python input function more closely.
Python输入()
Python中有Python输入函数builtins.py
. It reads a string from standard input and the trailing newline is stripped.
当input()
statement is executed then the program get paused until user gives the input and hit the enter key.
input()
returns the string that is given as user input without the trailing newline.
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()方法返回字符串从键盘输入得到的。要执行我们真正想要的操作,我们必须按如下方式将其转换为整数:
c = int(a) + int(b)
现在它将输出:
45
12
a + b = 45 + 12 = 57
所以,在接受输入后,按照您想要的方式进行转换。
带字符串消息的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
function is that it raises an error if the user hits EOF ( for *nix: Ctrl-D, Windows: Ctrl-Z+Return). The raised error is EOFError
. In the above example if you press Ctrl-D then you will see the output as:
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
这是关于python输入函数和如何在python中获得用户输入的快速综述。