- 接受用户输入 input()函数
message = input("Tell me something , and i will repeat it back to you :")
print(message)
- 获取数值输入——默认input()将用户输入处理为字符串
age = input("How old are you? :")
print(age)
age = int(age)#int()函数将字符串处理为数值
print(age>=18)
height = input("How tall are you , in inches?")
height = int(height)
if height >= 36:
print("\nYou are tall enough to ride !")
else:
print("\nYou will be able to ride when you are a little older .")
- while循环
current_number = 1
while current_number <= 5:
print(current_number)
current_number+= 1 #current_number = current_number + 1
- 让用户决定何时退出
current_number = 1
while current_number <= 5:
print(current_number)
current_number+= 1 #current_number = current_number + 1
prompt = "\nTell me something , and i will repeat it : "
prompt+= "\nEnter 'quit' to end the program \n"
message = ""
while message != "quit":
message = input(prompt)
if message != "quit":
print(message)
- 标志
prompt = "\nTell me something , and i will repeat it : "
prompt+= "\nEnter 'quit' to end the program \n"
active = True #active作为标志
while active:
message = input(prompt)
if message == "quit":
active = False
else:
print(message)
- break 退出循环
prompt = "\nTell me something , and i will repeat it : "
prompt+= "\nEnter 'quit' to end the program \n"
while True:
message = input(prompt)
if message == "quit":
break
else:
print(message)
- 在循环中使用continue
current_number = 0
while current_number < 10:
current_number+= 1
if current_number % 2 == 0:
continue
else:
print(current_number)
-
避免无限循环
-
使用while 处理列表
unconfirmed_users = ["alice","brain","candace"]
confirmed_users = []
while unconfirmed_users :
current_user = unconfirmed_users.pop()
print("Vertifying user :"+current_user.title())
confirmed_users.append(current_user)
print("\nThe following users have been confirmed: ")
for confirmed_user in confirmed_users:
print(confirmed_user.tilte())
- 使用while来批量移除列表中包含特定值的元素
#删除包含特定值的所有列表元素
pets = ["dog","cat","dog","goldfish","cat","rabbit","cat"]
print(pets)
while "cat" in pets:
pets.remove("cat")#使用方法remove()移除包含特定值的元素
print(pets)
- 使用用户输入来填充字典
polling_active = True
while polling_active:
name = input ("\nWhat is your name?\n")
response = input("Which mountain would you like to climb someday?\n")
#将答案储存在字典中,以输入的name作为键,response作为值
responses[name] = response
repeat = input("Would you like to let another person respond? (yes/no)")
if repeat == "no":
polling_active = False
print("\n---Poll Result---")
for name, response in responses.items():
print(name+" Would you like to climb "+response+" !")