Python 简明教程
Python - User Input
Provide User Input in Python
在本章中,我们将学习 Python 如何从控制台接受用户输入,并在同一控制台上显示输出。
In this chapter, we will learn how Python accepts the user input from the console, and displays the output on the same console.
每个计算机应用程序在运行时都应具备接受用户输入的功能。这使应用程序具有交互性。根据开发方式,应用程序可以接受用户以控制台中输入的文本 (sys.stdin) 、图形布局或基于 Web 的界面形式输入。
Every computer application should have a provision to accept input from the user when it is running. This makes the application interactive. Depending on how it is developed, an application may accept the user input in the form of text entered in the console (sys.stdin), a graphical layout, or a web-based interface.
Python User Input Functions
Python 为我们提供了两个内置函数来从键盘读取输入。
Python provides us with two built-in functions to read the input from the keyboard.
-
The input () Function
-
The raw_input () Function
Python 解释器以交互和脚本模式工作。虽然交互模式适合快速评估,但效率较低。对于重复执行相同指令集,应该使用脚本模式。
Python interpreter works in interactive and scripted mode. While the interactive mode is good for quick evaluations, it is less productive. For repeated execution of same set of instructions, scripted mode should be used.
让我们编写一个简单的 Python 脚本来开始。
Let us write a simple Python script to start with.
#! /usr/bin/python3.11
name = "Kiran"
city = "Hyderabad"
print ("Hello My name is", name)
print ("I am from", city)
将上述代码另存为 hello.py,并从命令行中运行。以下是输出结果:
Save the above code as hello.py and run it from the command-line. Here’s the output
C:\python311> python hello.py
Hello My name is Kiran
I am from Hyderabad
该程序只是打印程序中两个变量的值。如果你重复运行该程序,每次都会显示相同的输出。若要将该程序用于其他姓名和城市,你可以编辑代码,将 name 改为“Ravi”,将 city 改为“Chennai”。每次需要指定不同的值时,你都必须编辑该程序,保存并运行代码,这不是理想的方式。
The program simply prints the values of the two variables in it. If you run the program repeatedly, the same output will be displayed every time. To use the program for another name and city, you can edit the code, change name to say "Ravi" and city to "Chennai". Every time you need to assign different value, you will have to edit the program, save and run, which is not the ideal way.
The input() Function
显然,你需要在运行期间(程序正在运行)指定变量不同的机制。Python 的 input() 函数执行相同的工作。
Obviously, you need some mechanism to assign different value to the variable in the runtime − while the program is running. Python’s input() function does the same job.
以下是 Python 标准库 input() 函数的语法。
Following is the syntax of Python’s standard library input() function.
>>> var = input()
当解释器遇到 input() 函数时,它会一直等待用户从标准输入流(键盘)输入数据,直到按 Enter 键。可以将字符序列存储在字符串变量中以供以后使用。
When the interpreter encounters input() function, it waits for the user to enter data from the standard input stream (keyboard) till the Enter key is pressed. The sequence of characters may be stored in a string variable for further use.
在读取 Enter 键后,程序会继续执行下一条语句。让我们更改程序,将用户输入存储在 name 和 city 变量中。
On reading the Enter key, the program proceeds to the next statement. Let use change our program to store the user input in name and city variables.
#! /usr/bin/python3.11
name = input()
city = input()
print ("Hello My name is", name)
print ("I am from ", city)
运行时,你会发现光标在等待用户输入。输入 name 和 city 的值。使用输入的数据,输出结果会显示。
When you run, you will find the cursor waiting for user’s input. Enter values for name and city. Using the entered data, the output will be displayed.
Ravi
Chennai
Hello My name is Ravi
I am from Chennai
现在,程序中并未为变量指定任何特定值。每次运行时,都可输入不同的值。因此,你的程序已经成为真正的交互式程序。
Now, the variables are not assigned any specific value in the program. Every time you run, different values can be input. So, your program has become truly interactive.
在 input() 函数中,你可以提供一个 prompt 文本,在运行代码时,该文本会出现在光标前。
Inside the input() function, you may give a prompt text, which will appear before the cursor when you run the code.
#! /usr/bin/python3.11
name = input("Enter your name : ")
city = input("Enter your city : ")
print ("Hello My name is", name)
print ("I am from ", city)
运行程序时,它会显示提示消息,实质上帮助用户输入内容。
When you run the program displays the prompt message, basically helping the user what to enter.
Enter your name: Praveen Rao
Enter your city: Bengaluru
Hello My name is Praveen Rao
I am from Bengaluru
The raw_input() Function
raw_input() 函数的工作方式类似于 input() 函数。这里,需要注意的是,此函数在 Python 2.7 中可用,并且在 Python 3.6 中已将其重命名为 input() 。
The raw_input() function works similar to input() function. Here only point is that this function was available in Python 2.7, and it has been renamed to input() in Python 3.6
以下是 raw_input() 函数的语法:
Following is the syntax of the raw_input() function:
>>> var = raw_input ([prompt text])
让我们使用 raw_input() 函数重写以上程序:
Let’s re-write the above program using raw_input() function:
#! /usr/bin/python3.11
name = raw_input("Eneter your name - ")
city = raw_input("Enter city name - ")
print ("Hello My name is", name)
print ("I am from ", city)
运行时,你会发现光标在等待用户输入。输入 name 和 city 的值。使用输入的数据,输出结果会显示。
When you run, you will find the cursor waiting for user’s input. Enter values for name and city. Using the entered data, the output will be displayed.
Eneter your name - Ravi
Enter city name - Chennai
Hello My name is Ravi
I am from Chennai
Taking Numeric Input in Python
我们编写一段 Python 代码,它从用户处获取矩形的宽度和高度,并计算面积。
Let us write a Python code that accepts width and height of a rectangle from the user and computes the area.
#! /usr/bin/python3.11
width = input("Enter width : ")
height = input("Enter height : ")
area = width*height
print ("Area of rectangle = ", area)
运行程序并输入宽度和高度。
Run the program, and enter width and height.
Enter width: 20
Enter height: 30
Traceback (most recent call last):
File "C:\Python311\var1.py", line 5, in <module>
area = width*height
TypeError: can't multiply sequence by non-int of type 'str'
你为什么在这里得到一个 TypeError ?原因在于,Python 始终将用户输入作为字符串进行读取。因此,width="20" 和 height="30" 是字符串,显然你不能对两个字符串进行乘法运算。
Why do you get a TypeError here? The reason is, Python always read the user input as a string. Hence, width="20" and height="30" are the strings and obviously you cannot perform multiplication of two strings.
为克服这一问题,我们将使用 int() ,这是 Python 标准库中的另一个内置函数。它将字符串对象转换为整数。
To overcome this problem, we shall use int(), another built-in function from Python’s standard library. It converts a string object to an integer.
为从用户处获取整数输入,以字符串形式读取输入,然后使用 int() 函数将其类型转换为整数:
To accept an integer input from the user, read the input in a string, and type cast it to integer with int() function −
w = input("Enter width : ")
width = int(w)
h = input("Enter height : ")
height = int(h)
你可以将 input 和类型转换语句组合到一个语句中:
You can combine the input and type cast statements in one −
#! /usr/bin/python3.11
width = int(input("Enter width : "))
height = int(input("Enter height : "))
area = width*height
print ("Area of rectangle = ", area)
现在,你可以向程序中的两个变量输入任何整数值:
Now you can input any integer value to the two variables in the program −
Enter width: 20
Enter height: 30
Area of rectangle = 600
Python 的 float() 函数将字符串转换为浮点对象。以下程序接受用户输入并将其解析为浮点变量 rate,并计算用户输入的金额的利息。
Python’s float() function converts a string into a float object. The following program accepts the user input and parses it to a float variable − rate, and computes the interest on an amount which is also input by the user.
#! /usr/bin/python3.11
amount = float(input("Enter Amount : "))
rate = float(input("Enter rate of interest : "))
interest = amount*rate/100
print ("Amount: ", amount, "Interest: ", interest)
该程序要求用户输入金额和汇率;并显示结果如下 −
The program ask user to enter amount and rate; and displays the result as follows −
Enter Amount: 12500
Enter rate of interest: 6.5
Amount: 12500.0 Interest: 812.5
The print() Function
Python 的 print() 函数是一个内置函数。它是最常用的函数,它在 Python 的控制台或标准输出 (sys.stdout) 上显示括号中给出的 Python 表达式的值。
Python’s print() function is a built-in function. It is the most frequently used function, that displays value of Python expression given in parenthesis, on Python’s console, or standard output (sys.stdout).
print ("Hello World ")
括号内可以包含任意数量的 Python 表达式。他们必须以逗号符号分隔。列表中的每个项目可以是任何 Python 对象或有效的 Python 表达式。
Any number of Python expressions can be there inside the parenthesis. They must be separated by comma symbol. Each item in the list may be any Python object, or a valid Python expression.
#! /usr/bin/python3.11
a = "Hello World"
b = 100
c = 25.50
d = 5+6j
print ("Message: a)
print (b, c, b-c)
print(pow(100, 0.5), pow(c,2))
对 print() 的第一次调用显示了一个字符串文字和一个字符串变量。第二个打印两个变量的值和它们的减法。 pow() 函数计算一个数字的平方根和一个变量的平方。
The first call to print() displays a string literal and a string variable. The second prints value of two variables and their subtraction. The pow() function computes the square root of a number and square value of a variable.
Message Hello World
100 25.5 74.5
10.0 650.25
如果 print() 函数的括号中有多个用逗号分隔的对象,这些值将用一个空格 " " 分隔。要将任何其他字符用作分隔符,请为 print() 函数定义一个 sep 参数。该参数应跟随要打印的表达式列表。
If there are multiple comma separated objects in the print() function’s parenthesis, the values are separated by a white space " ". To use any other character as a separator, define a sep parameter for the print() function. This parameter should follow the list of expressions to be printed.
在 print() 函数的以下输出中,变量用逗号分隔。
In the following output of print() function, the variables are separated by comma.
#! /usr/bin/python3.11
city="Hyderabad"
state="Telangana"
country="India"
print(city, state, country, sep=',')
sep=',' 的效果可以在结果中看到 −
The effect of sep=',' can be seen in the result −
Hyderabad,Telangana,India
print() 函数默认情况下在末尾发出一个换行符 ('\n')。因此,下一个 print() 语句的输出将出现在控制台的下一行。
The print() function issues a newline character ('\n') at the end, by default. As a result, the output of the next print() statement appears in the next line of the console.
city="Hyderabad"
state="Telangana"
print("City:", city)
print("State:", state)
两行显示为输出 −
Two lines are displayed as the output −
City: Hyderabad
State: Telangana
要使这两行出现在同一行中,请在第一个 print() 函数中定义 end 参数并将其设置为一个空格字符串 " "。
To make these two lines appear in the same line, define end parameter in the first print() function and set it to a whitespace string " ".
city="Hyderabad"
state="Telangana"
country="India"
print("City:", city, end=" ")
print("State:", state)
两个 print() 函数的输出都将继续出现。
Output of both the print() functions appear in continuation.
City: Hyderabad State: Telangana