一、函数input()工作原理
函数input()接受一个参数:即要向用户显示的提示和说明。
Sublime Text不能运行提示用户输入的程序。可以用Sublime Text编写提示用户输入的程序,但必须从终端运行它们。
使用int()来获取数值输入:由于使用函数input()时,Python将用户输入解读为字符串。所以在需要使用数值的情况下,用int()进行类型转换。
在python2.7中使用raw_input()来获取用户输入。
二、while循环简介
1、使用while循环
for循环用于针对集合中的每个元素的一个代码块。而while循环不断地运行,直到指定条件不满足为止。
2、让用户选择何时退出
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':
print(message)
3、使用标志
在更复杂的程序环境中,很多不同事件都会导致程序停止运行。此时,可定义一个变量,用来判断程序是否处于活动状态。这个变量被称为标志。
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)
4、使用break退出循环
要立即退出while循环,不再运行循环中余下的代码,也不管条件测试的结果如何,可使用break语句。
在任何Python循环中都可使用break语句。例如,可使用break语句退出遍历列表或字典的for循环。
prompt = '\nPlease enter a 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() + '!')
5、在循环中使用continue
要返回到循环开头,并根据条件测试结果决定是否继续执行循环,可使用continue语句。
current_number = 0
while current_number < 10:
current_number += 1
if current_number % 2 == 0:
continue
else:
print(current_number)
注:如果程序陷入无限循环,按Ctrl+C停止,也可直接关闭终端窗口。
三、使用while循环处理列表和字典
要在遍历列表的同时对其进行修改,可使用while循环。
1、在列表之间移动元素
假设有一个列表其中包含新注册但还未验证的网站用户;验证这些用户后,就需要将他们移到另一个已验证用户列表中。
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())
2、删除包含特定值的所有列表元素
通过在while中使用方法remove()删除列表中包含特定值的所有元素。
3、使用用户输入来填充字典
使用while循环提示用户输入任意数量的信息。
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 response?"+
"(yes/no)")
if repeat == 'no':
polling_active = False
print('\n-------------Poll Result----------')
for name,response in responses.items():
print(name + ' would like to climb ' + response + '.')