Chapter 7 User Input and while Loops
7.1 How the input() Function Works
7.1.1 A Simple Example
message = input("Tell me something, and I will repeat it back to you: ")
print(message)
把input的内容赋给了一个变量。
7.1.2 多行显示prompt:
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(f"\nHello, {name}!")
7.1.3 Using int() to Accept Numerical Input
输入的都是字符串。若要转变成数字格式,用int()
height = input("How tall are you, in inches? ")
height = int(height)
if height >= 48:
print("\nYou're tall enough to ride!")
7.1.4 The Modulo Operator(%) 求模运算符
求余数。可用于判断奇偶数。
>>> 4 % 3
1
>>> 5 % 3
2
>>> 6 % 3
0
7.2 Introducing while Loops
7.2.1 An Example
prompt = "\nTell 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)
在进入while循环后显示prompt.
7.2.2 Using a Flag
For a program that should run only as long as many conditions are true, you can define one variable that determines whether or not the entire program is active. This variable, called a flag, acts as a signal to the program.
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)
7.2.3 Using break to Exit a Loop
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()}!")
7.1.4 Using continue in a Loop
输出奇数:
current_number = 0
while current_number < 10:
current_number += 1
if current_number % 2 == 0:
continue
print(current_number)
7.3 Using a while Loop with Lists and Dictionaries
7.3.1 Moving Items from One List to Another
# Start with users that need to be verified,
# and an empty list to hold confirmed users.
unconfirmed_users = ['alice', 'brian', 'candace']
confirmed_users = []
# Verify each user until there are no more unconfirmed users.
# Move each verified user into the list of confirmed users.
while unconfirmed_users:
current_user = unconfirmed_users.pop()
print(f"Verifying user: {current_user.title()}")
confirmed_users.append(current_user)
# Display all confirmed users.
print("\nThe following users have been confirmed:")
for confirmed_user in confirmed_users:
print(confirmed_user.title())
未完