python中接受用户输入需要使用函数 input()
- input函数工作原理
函数input()让程序暂停运行,等待用户输入一些文本。input返回用户输入内容,再将其存入变量即可获得用户输入。例如:
message = input("Tell me something, and I will repeat it back to you: ")
print(message)
输入Hello Red,按回车返回输入的值:

函数input()接受一个参数:即要向用户显示的提示或说明,让用户知道该如何做。
input()函数中的提示可能超过一行,在这种情况下可以将提示存储在一个变量中,再将该变量传递给函数input()。例如:
prompt = "If you tell us who you are,we can personalize the messages you see." prompt += "\nWhat is you first name?\n" name = input(prompt) print("\nHello,"+name+"!")

Python中,用户输入的值input()函数都解读为字符串,需要转为数值型时,可直接使用int()函数进行转换。例如:
age = input("How old are you? ")
age = int(age)
- while循环简介
for循环用于针对集合中的每个元素都一个代码块,而while循环不断地运行,直到指定的条件不满足为止。
要立即退出while循环,不再运行循环中余下的代码,也不管条件测试的结果如何,可以使用break语句。
要返回到循环开头,并根据条件测试结果决定是否继续执行循环,可使用continue语句,它不像break语句那样不再执行余下的代码并退出整个循环。
- 使用while循环来处理列表和字典
使用while循环移动列表之间元素
unconfirmed_users = ['A','C','F','B'] confirmed_users = [] while unconfirmed_users: current_user = unconfirmed_users.pop() confirmed_users.append(current_user) print(confirmed_users)
删除包含特定值的所有列表元素,函数remove()可以删除列表中的特定值,但是使用while循环和remove()结合可以删除列表中包含特定值得所有元素。例如:
pets = ['dog','cat','dog','fish','cat','rabbit','cat'] print(pets) while 'cat' in pets: pets.remove('cat') print(pets)
使用while循环来提示用户输入任意数量的信息,将用户输入来填充字典,例如:
#coding=gbk responses = {} active = True while 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? (Y/N)") if repeat == 'N': active = False for name,response in responses.items(): print(name+"would like to climb "+response+".")
posted on
浙公网安备 33010602011771号