函数input()的工作原理
函数input()让程序暂停运行,等待用户输入一些文本。获取用户输入后,Python将其存储在一个变量中,方便使用。 例如:
message = input("Tell me something, and I will repeat it back to you: ")
print(message)
函数input()接受一个参数:要向用户显示的提示或说明,程序等待用户输入,并在用户按回车键后继续运行。输入存储在变量message中,接下来的print(message)将输入呈现给用户:
Tell me something, and I will repeat it back to you:Hello everyone!
Hello everyone!
注意:Sublime Text不能运行提示用户输入的程序。
1.编写清晰的程序
当你使用函数input()时,都应指定清晰而易于明白的提示,准确地指出你希望用户提供什么样的信息——指出用户该输入任何信息的提示都行。
如下所示:
name = input("Please enter your name: ")
print("Hello, "+name+"!")
通过在提示末尾(这里是冒号后面)包含一个空格,可将提示与用户输入分开,让用户清楚地知道其输入始于何处,如下所示:
Please enter your name:Eric
Hello, Eric!
需要指出获取特定输入的原因。在这种情况下,可将提示存储在一个变量中,再将该变量传递给函数input()。这样,即便提示超过一行,input()语句也非常清晰。
prompt = "If you tell us who you are, we can personalize the messages you see."
prompt+= "\nWhat is your first name? "
name = input(prompt)
print("\nHello, "+name+"!")
演示了一种创建多行字符串的方式。
第1行将消息的前半部分存储在变量prompt中;在第2行中,运算符+=在存储在prompt中的字符串末尾附加一个字符串。
最终的提示横跨两行,并在问号后面包含一个空格,
打印结果为:
If you tell us who you are, we can personalize the messages you see.
What is your first name? Eric
Hello, Eric!
2.使用int()来获取数值输入
使用函数input()时,Python将用户输入解读为字符串。 例如:
>>>age = input("How old are you? ")
How old are you? 21
>>>age
'21'
用户输入的是数字21,但我们请求Python提供变量age的值时,它返回的是'21'——用户输入的数值的字符串表示。
age = input("How old are you? ")
How old are you? 21
age >= 18
Traceback (most recent call last):
File "", line 1, in
TypeError: unorderable types: str() >= int()
你试图将输入用于数值比较时,Python会引发错误,因为它无法将字符串和整数进行比较:不能将存储在age中的字符串'21'与数值18进行比较。
为解决这个问题,可使用函数int(),它让Python将输入视为数值。函数int()将数字的字符串表示转换为数值表示,如下所示:
>>>age = input("How old are you? ")
How old are you? 21
>>>age = int(age)
>>>age >= 18
True
如何在实际程序中使用函数int()呢?
下面的程序,它判断一个人是否满足坐过山车的身高要求:
height = input("How tall are you, in inches? ")
height = int(height)
if height >= 36:
print("\nYou're tall enough to ride!")
else:
print("\nYou'll be able to ride when you're a little older.")
打印结果为:
How tall are you, in inches? 66
You're tall enough to ride!
How tall are you, in inches? 12
You'll be able to ride when you're a little older.
将数值输入用于计算和比较前,务必将其转换为数值表示。
3.求模运算符
处理数值信息时,求模运算符(%)是一个很有用的工具,它将两个数相除并返回余数:
>>>4 % 3
1
>>>5 % 3
2
>>>6 % 3
0
>>>7 % 3
1
求模运算符不会指出一个数是另一个数的多少倍,而只指出余数是多少。
如果一个数可被另一个数整除,余数就为0,因此求模运算符将返回0。
可利用这一点来判断一个数是奇数还是偶数:
number = input("Enter a number, and I'll tell you if it's even or odd: ")
number = int(number)
if number % 2 == 0:
print("\nThe number "+str(number)+" is even.")
else:
print("\nThe number "+str(number)+" is odd.")
偶数都能被2整除,因此对一个数(number)和2执行求模运算的结果为零,即number % 2 == 0,那么这个数就是偶数;否则就是奇数。
Enter a number, and I'll tell you if it's even or odd:42
The number 42 is even.