6.1用户输入
在Python中用户输入需要使用到函数input()来进行用户输入信息的获取。函数input()可以使得程序暂停运行,等待用户输入一些文本,待用户输入后将其存储在变量中来方便使用。
message=intput("Tell me something,and I will repeat it back to you: ")
print(message)
在使用函数input()时,都应指定清晰而易于明白的提示,准确地指出你希望用户提供什么样地信息。在提示末尾一般都会留有一个空格可将提示与用户输入分开,让用户清楚的知道其输入始于何处。
使用int()来获取数值输入
在使用函数input()时,Python将用户输入解读为字符串。这时候如果用户输入的是数字时便很有可能在使用过程中出现问题,因为时字符串打印输出并不会出错,可当想要将它作为数字使用时就会引发错误。
函数int()将数字的字符串表示转换为数值表示。
age=input("How old are you?")
age=int(age)
求模运算符(%)
在处理数值信息时,求模运算符(%)是一个很有用的工具,它将两个数相除并返回余数。
6.2while循环简介
for循环用于针对集合中的每个元素都一个代码块,而while循环不断地运行,直到指定的条件不满足为止。
current_number=1
while current_number<=5:
print(current_number)
current_number+=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)
print(message)
标志使用
我们可以定义一个变量,用于判断整个程序是否处于活动状态,这个变量称为标志。这样在while语句中就只需检查一个条件——来检测标志是否满足。
使用break退出循环
要立即退出while循环,不再运行循环中余下的代码,可以使用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()+"!")
在循环中使用continue
要返回到循环开头,并根据条件测试结果决定是否继续执行循环,可使用continue语句,它不同于break语句那样直接退出整个循环。
例如下面这个只打印奇数的循环:
current_number=0
while current_number<10:
current_number +=1
if current_number%2==0:
continue
print(current_number)
6.3while循环在列表和字典中的使用
在列表之间移动元素
这里有一个案例,在一个列表中是新注册但未验证的网站用户,当用户通过验证之后便可以将他们移动到另一个列表中去,此处便采用while循环来进行元素的移动。
unconfirmed_users=['alice','brian','candance']
confirmed_users=[]
while unconfirmed_users:
current_user=unconfirmed_users.pop()
print("Verifying user: "+current_user.title())
confirmed_users.append(current_user)
删除包含特定值的所有列表元素
pets=['dog','cat','dog','goldfish','cat','rabbit','cat']
while 'cat' in pets:
pets.remove('cat')
使用用户输入来填充字典
responses={}
polling_active=Ture #标志
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