Python学习笔记-input()用户输入和while循环

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/hhw999/article/details/89668384

1、input()函数

  • input()函数使程序暂停运行,等待用户输入一些文本,用户输入后,python将文本存储在一个变量中。
  1. 简单使用
message = input("Name:")
print("Your name is:" + message)

show = "Name:"
message = input(show)
print(message)
  1. 使用int()来获取数值输入
age = input("How old are you? ")
age = int(age)
if age >18:
	print(">18")
else:
	print("<=18")

2、while循环

  1. 简单循环
current_number = 1
while current_number <= 5:
	print(current_number)
	current_number += 1				#控制循环变量
  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)
	if message != 'quit':								#避免输出'quit'
		print(message)
  1. 使用检测标志
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)
  1. 使用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("I'd love to go to " + city.title() + ".")
  1. 使用continue退出循环(仅退出当前的一轮循环)
current_number = 0
while current_number < 10:
	current_number += 1
	if current_number % 2 == 0:
		continue				#后面的print不执行,回到while判断循环条件
	print(current_number)
  1. 使用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列表中值为'cat'的元素
pets = ['dog', 'cat', 'dog', 'goldfish', 'cat', 'rabbit', 'cat']
print(pets)

while 'cat' in pets:
	pets.remove('cat')

print(pets)
  • 使用用户输入来填充字典
responses = {}

#设置标志,用于控制循环
active = True

while active:
	#用户输入信息
	name = input("What's 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':
		active = False

#显示结果
print('-' * 20)
for name,response in responses.items():
	print(name + " would like to climb " + response + ".")
展开阅读全文

没有更多推荐了,返回首页