python 第七章 用户输入和while循环
# input()函数:input()函数会暂停程序的执行,并等待用户输入一些文本,并且input函数可以接收一个参数,即要向用户显示的提示。
message = input("Tell me something, and I will repeat it back to you: ")
print(message)
# int()函数:因为使用input()函数获取的输入都是默认为字符串,使用int()函数可以将字符串转为整型。
# float()函数:因为使用input()函数获取的输入都是默认为字符串,使用float()函数可以将字符串转为浮点型。
age = input("How old are you? ")
print(type(age))
print(age)
age = int(age)
print(type(age))
print(age)
age=float(age)
print(type(age))
print(age)
# 求模运算符%:将两个数相除,并返回余数
print(5%3)
# while循环:while循环和for循环一样,都是重复执行一些代码,但是for循环一般是用来遍历列表中的元素,而while循环一般是用来重复执行一段代码,直到满足某些条件为止。
i = 1
while i <= 5:
print(i)
i += 1 # 这个是必须要的啊,不然就是死循环了
# 让用户选择何时退出
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)
# 使用标志:标志是一种在程序运行期间使用的变量,用于跟踪程序是否应该运行某个特定块代码。
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)
# 使用break退出循环:break语句用来控制程序流程,,可用来控制哪些代码行将执行、哪些代码行不执行,从而让程序按你的要求执行你要执行的代码。
while True:
city = input("\nPlease input a city you have visited: ")
if city == 'quit':
break
else:
print("I'd love to go to " + city.title() + "!")
# 在所有python循环中都可使用break语句。例如,可使用break语句来退出遍历列表或字典的for循环。
# 在循环中使用continue语句:continue语句会告诉Python跳过当前循环中余下的代码,并继续进行下一轮循环。
current_number = 0
while current_number < 10:
current_number += 1
if current_number % 2 == 0:
continue
print(current_number)
# 尽量避免上面所说的死循环,如果死循环了,可以尝试使用Ctrl+C来结束程序。
# 使用while循环处理列表和字典
# 在列表之间移动元素
unconfirmed_users = ['alice', 'brian', 'candace']
confirmed_users = []
while unconfirmed_users:
current_user = unconfirmed_users.pop()
print("Verifying 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.title())
# 删除为特定值的所有列表元素
pets = ['dog', 'cat', 'dog', 'goldfish', 'cat', 'rabbit', 'cat']
while 'cat' in pets:
pets.remove('cat')
print(pets)
# 使用用户输入填充字典
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(name + " would like to climb " + response + ".")
更多推荐


所有评论(0)