input获取用户输入
age = input("How old are you? ")
int()
int()函数可以转换为整数
age = int(age)
if age >= 16:
print("You are an audlt")
Modulo Operator
取余
3 % 2 # 得到余数1
while循环
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)
print(message)
break和continue的使用与在其他语言中一样
prompt = "Enter a number less than 10"
prompt += "\nEnter 0 to end the game: "
i = 0
while i < 10:
guess = int(input(prompt))
if guess == 0:
break
elif guess > 10:
i += 1
continue
else:
print("once again")
while在list和dictionary中的使用
sandwich_orders = ['ham', 'pastrami', 'apple',
'beacon', 'pastrami', 'tuna', 'pastrami']
finished_sandwiches = []
print("The Deli has run out of Pastrami")
while 'pastrami' in sandwich_orders:
sandwich_orders.remove('pastrami')
making = True
while making:
if sandwich_orders:
current = sandwich_orders.pop()
print(f"I made your {current} sandwiches")
finished_sandwiches.append(current)
else:
making = False
print(finished_sandwiches)
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
print("\n--- Poll Results ---")
for name, response in responses.items():
print(f"{name} would like to climb {response}")