你可以使用input()函数来获取用户输入
>>> message = input("Tell me something,and I will repeat it back to you:")
Tell me something,and I will repeat it back to you:Hello,everyone!
>>> print(message)
Hello,everyone!
当使用函数input()时,都应指定清晰易懂的提示,准确地指出希望用户提供什么样的信息---指出用户应该输入何种信息的任何提示都行。
有时候提示可能超过一行。例如,你可能需要指出获取特定输入的原因。在这种情况下,可将提示赋给一个变量,再将变量传递给函数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)
If you tell us who you are,we can personalize the messages you see.
What is your first name? Eric
>>> print(f"Hello {name}")
Hello Eric
使用int()来获取数值输入
使用函数Input()时,python将用户输入解读为字符串。请看下面让用户输入年龄的解释器会话。
>>> age = input("How old are you? ")
How old are you? 21
>>> age
'21'
用户输入的数是21,但我们请求Python提供变量age的值时,它返回的是‘21’---用户输入数值的字符串表示。我们怎么知道Python将输入解读成了字符串呢?因为这个数用引号括起来了。如果只想打印输入,这一点问题都没有,但是如果试图将输入作为数来使用,就会引发错误:
>>> age >= 18
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: '>=' not supported between instances of 'str' and 'int'
因为它无法将字符串和整数进行比较:不能将赋给age的字符串‘21’与数值18进行比较。
为了解决这个问题,可使用函数int(),它让Python将输入视为数值。函数int()将数的字符串表示转换为数值标识,如下所示:
>>> age = input("How old are you? ")
How old are you? 21
>>> age = int(age)
>>> age >= 18
True
用int()将字符串转换成了数值表示。这样Python就能运行条件测试了,将变量age(它现在表示的数值21)同18进行比较,看它是否大于或等于18。
求模运算%
>>> number = input("Enter a number,and I'll tell you if it's even or odd: ")
Enter a number,and I'll tell you if it's even or odd: 67
>>> if number % 2 == 0:
... print("\nThe number {number} is even!")
... else:
... print("\nThe number {number} is odd!")
...
>>>
>>>The number 67 is odd!
使用while循环
>>> current_number = 1
>>> while current_number <= 5:
... print(current_number)
... current_number += 1
...
1
2
3
4
5
使用while循环让用户选择何时退出
>>> prompt = "\n Tell me something, and I will repeat it back to you:"
>>> prompt += "\nEnter 'quit' to end the program. "
>>> message = ""
>>> while message != 'quit':
... message = input(prompt)
... print(message)
...
Tell me something, and I will repeat it back to you:
Enter 'quit' to end the program. Hello,everyone!
Hello,everyone!
Tell me something, and I will repeat it back to you:
Enter 'quit' to end the program. Hello again!
Hello again!
Tell me something, and I will repeat it back to you:
Enter 'quit' to end the program. quit
quit
这个程序很好,唯一美中不足的是,它将单词‘quit’也作为一条消息打印了出来,为修复这种问题,只需使用一个简单的if测试:
>>> prompt = "\n Tell me something, and I will repeat it back to you:"
>>> prompt += "\nEnter 'quit' to end the program. "
>>> message = ""
>>> while message != 'quit':
... message = input(prompt)
... if message != 'quit':
... print(message)
...
Tell me something, and I will repeat it back to you:
Enter 'quit' to end the program. Hello everyone!
Hello everyone!
Tell me something, and I will repeat it back to you:
Enter 'quit' to end the program. Hello again!
Hello again!
Tell me something, and I will repeat it back to you:
Enter 'quit' to end the program. quit
使用标志
>>> prompt = "\nTell me something ,and I will repeat it back to you:"
>>> prompt += "\nEnter 'quit' to end the program. "
>>> active = True
>>> while active:
... message = input(prompt)
... if message == 'quit':
... active = False
... else:
... print(message)
...
Tell me something ,and I will repeat it back to you:
Enter 'quit' to end the program. Hello everyone!
Hello everyone!
Tell me something ,and I will repeat it back to you:
Enter 'quit' to end the program. Hello again!
Hello again!
Tell me something ,and I will repeat it back to you:
Enter 'quit' to end the program. Hi!
Hi!
Tell me something ,and I will repeat it back to you:
Enter 'quit' to end the program. quit
使用break退出循环
要立即退出while循环,不再运行循环中余下的代码,也不管条件测试的结果如何,可使用break语句。
>>> prompt = "\nPlease enter the name of a city you have visited:"
>>> prompt += "\n(Enter 'quit' when you are finished.)"
>>> while True:
... city = input(prompt)
... if city == 'quit':
... break
... else:
... print(f"I'd love to go to {city.title()}!")
...
Please enter the name of a city you have visited:
(Enter 'quit' when you are finished.)New York
I'd love to go to New York!
Please enter the name of a city you have visited:
(Enter 'quit' when you are finished.)San Francisco
I'd love to go to San Francisco!
Please enter the name of a city you have visited:
(Enter 'quit' when you are finished.)quit
注意:在任何Python循环中都可使用break语句。例如,可使用break语句来退出遍历列表或字典的for循环。
在循环中使用continue
要返回循环开头,并根据条件测试结果决定是否继续执行循环,可使用continue语句,它不像break语句那样不再执行余下的代码并退出整个循环。
>>> current_number = 0
>>> while current_number < 10:
... current_number += 1
... if current_number % 2 == 0:
... continue
... print(current_number)
...
1
3
5
7
9
避免无限循环
每个while循环都必须有停止运行的途径,这样才不会没完没了地执行下去。
>>> x = 1
>>> while x <= 5:
... print(x)
... x += 1
...
1
2
3
4
5
如果程序陷入无限循环,可按Ctrl + C ,也可关闭显示输出的窗口。
while True:
print("Enter 'quit' when you are finished.")
age = input("请输入你的年龄:")
if age == 'quit':
break
elif int(age) < 3:
print("The price of you is free.")
elif 3 <= int(age) <12:
print("The price of you is $10.")
elif 12 <= int(age) :
print("The price of you is $15.")
使用while循环处理列表和字典
for循环是一种遍历列表的有效方式,但不应在for循环中修改列表,否则将导致Python难以跟踪其中的元素。要在遍历列表的同时对其进行修改,可使用while循环。通过将while循环同列表和字典结合起来使用,可收集、存储并组织大量输入,供以后查看和显示。
1、在列表之间移动元素
假设有一个列表包含新注册但还未验证的网站用户。验证这些用户后,如何将他们移到另一个已验证用户列表中呢?一种办法是使用一个while循环,在验证用户的同时将其从未验证用户列表中提取出来,再将其加入另一个已验证用户列表中。
>>> #首先,创建一个待验证用户列表
>>> #和一个用于存储已验证用户的空列表。
>>> unconfirmed_users = ['alice','brian','candace']
>>> confirmed_users = []
>>> #验证每个用户,直到没有未验证用户为止。
>>> # 将每个经过验证的用户都移到已验证用户列表中。
>>> while unconfirmed_users:
... current_user = unconfirmed_users.pop()
... print(f"Verifying user : {current_user.title()}")
... confirmed_users.append(current_user)
...
Verifying user : Candace
Verifying user : Brian
Verifying user : Alice
>>> #显示所有已验证的用户。
>>> print("\nThe following users have been confirmed:")
The following users have been confirmed:
>>> for confirmed_user in confirmed_users:
... print(confirmed_user.title())
...
Candace
Brian
Alice
2、删除为特定值的所有列表元素
假设你有一个宠物列表,其中包含多个值为‘cat’的元素。要删除所有这些元素,可不断运行一个while循环,直到列表中不再包含值'cat',如下所示。
>>> pets = ['dog','cat','dog','goldfish','cat','rabbit','cat']
>>> print(pets)
['dog', 'cat', 'dog', 'goldfish', 'cat', 'rabbit', 'cat']
>>> while 'cat' in pets:
... pets.remove('cat')
...
>>> print(pets)
['dog', 'dog', 'goldfish', 'rabbit']
3、使用用户输入来填充字典
可使用while循环提示用户输入任意多地信息。下面创建一个调查程序,其中的循环每次执行时都提示输入被调查者的名字和回答。我们将收集的数据存储在一个字典中,以便将会大同被调查者关联起来
>>> responses = {}
>>> #设置一个标志,指出调查是否继续
>>> polling_active = True
>>> while polling_active:
... #提示输入被调查者的名字和回答。
... name = input("\nWhat is your name? ")
... response = input("Which mountain would you like to climb someday? ")
... #将回答存储在字典中
... responses[name]=response
... #看看是否还有人要参与调查
... repeat = input("Would you like to let another person respond?(yes/no)")
... if repeat == 'no':
... polling_active = False
...
What is your name? aa
Which mountain would you like to climb someday? Denali
Would you like to let another person respond?(yes/no)yes
What is your name? bb
Which mountain would you like to climb someday? Devil's Thumb
Would you like to let another person respond?(yes/no)no
>>> #调查结果显示
>>> print("\n---Poll Results---")
---Poll Results---
>>> for name,response in responses.items():
... print(f"{name} would like to climb {response}.")
...
aa would like to climb Denali.
bb would like to climb Devil's Thumb.