许多程序旨在为用户解决实际问题。为此,他们需要接收用户的输入。
- 例如,旨在检查用户是否达到投票年龄的程序要求用户输入其年龄。
根据输入,程序可以执行计算或比较,并向用户提供反馈。
input()函数:
input() 函数用于提示用户输入一些数据。
它会暂停程序,等待用户的输入,并将输入分配给变量。
message = input("Tell me something, and I will repeat it back to you: ")
print(message)
>>
Tell me something, and I will repeat it back to you: Hello everyone!
Hello everyone!
input() 函数接受一个参数:一个提示,告诉用户要输入什么类型的信息。
编写 Clear 提示:
- 清晰、结构良好的提示对于从用户那里获得正确的输入至关重要。
name = input("Please enter your name: ")
print(f"\nHello, {name}!")
>>
Please enter your name: Nidhi
Hello, Nidhi!
- 添加空格并将提示与输入分开,使用户更容易知道在何处输入数据。
- 可以使用字符串连接将较长的提示分成多行,这有助于解释为什么需要某些输入。
prompt = "If you share your name, we can personalize the messages you see."
prompt += "\nWhat is your first name? "
name = input(prompt)
print(f"\nHello, {name}!")
>>
If you share your name, we can personalize the messages you see.
What is your first name? Nidhi
Hello, Nidhi!
使用int()将输入转换为数字:
默认情况下,input() 函数将所有用户输入解释为字符串,即使用户输入的是数字也是如此。
age = input("How old are you? ")
How old are you? 21
>>>
age
'21'
如果需要执行计算或比较(例如,检查用户的年龄是否大于 18),则必须使用 int() 函数将输入转换为整数。
age = input("How old are you? ")
age = int(age) # Convert the input string to an integer
if age >= 18:
print("You are old enough to vote.")
>>
How old are you? 18
You are old enough to vote.
处理数值输入:
数值输入可以以多种方式使用,例如进行比较或执行计算。
height = input("How tall are you, in inches? ")
height = int(height)
if height >= 48:
print("You're tall enough to ride!")
else:
print("You'll be able to ride when you're a little older.")
>>
How tall are you, in inches? 22
You'll be able to ride when you're a little older.
模运算符 (%):
模运算符将一个数字除以另一个数字并返回余数。
这对于确定一个数字是否能被另一个数字整除(例如,一个数字是偶数还是奇数)很有用。
number = input("Enter a number, and I'll tell you if it's even or odd: ")
number = int(number)
if number % 2 == 0:
print(f"The number {number} is even.")
else:
print(f"The number {number} is odd.")
>>
Enter a number, and I'll tell you if it's even or odd: 7458942342
The number 7458942342 is even