1 函数input()的工作原理
message=input("Tell me something,and I will repeat it back to you:")
print(message)
1.1 编写清晰的程序
name=input("Please enter your name:")
print("Hello,"+name+"!")
1.2 使用int()来获取数值输入
age=input("How old are you?")
age=int(age)
age>=18
height=input("How tall are you,in inches?")
height=int(height)
if height >=36:
print(" You"re tall enough to ride!")
else:
print(" You"ll be able to ride when you"re a little older.")
1.3 求模运算符
求模运算符(%),它将两个数相除并返回余数。
number=input("Enter a number,and I"ll tell you if it"s even or odd:")
number=int(number)
if number % 2==0:
print(" The number"+str(number)+"is even.")
else:
print(" The number"+str(number)+"is odd.")
2 while循环
for循环用于针对集合中的每个元素的一个代码块,而while循环不断地运行,直到指定的条件不满足为止。
current_number=1
while current_number<5:
print(current_number)
current_number+=1
2.1 让用户选择何时退出
prompt=" Tell me somnething,and I will repeat it back to you:"
prompt+=" Enter quit to end the program."
message=" "
while message!="quit":
message=input(prompt)
if message!="quit":
print(message)
2.2 使用标志
在要求很多条件都满足才继续运行的程序中,可定义一个变量,用于判断整个程序是否处于活动状态,这个变量被称为标志。充当了程序的交通信号灯。
prompt=" Tell me somnething,and I will repeat it back to you:"
prompt+=" Enter quit to end the program."
active=True
while active:
message=input(prompt)
if message=="quit":
active=False
else:
print(message)
2.3 使用break退出循环
要立即退出while循环,不再运行循环中余下的代码,也不管条件测试的结果如何,可使用break语句。break语句用于控制程序流程,可使用它来控制哪些代码行将执行,哪些代码行不执行,从而让程序按你的要求执行你要执行的代码。
prompt=" Please enter the name of a city you have visited:"
prompt+=" (Enter quit when you are finished.)"
while True:
city=input(prompt)
if city=="quit":
break
else:
print("T"d love to go to"+city.title()+"!")
2.4 在循环中使用continue
current_number=0
while current_number<10:
current_number+=1
if current_number % 2==0:
continue
print(current_number)
可按Ctrl+C,关闭显示程序输出的终端窗口。
3 使用while循环来处理列表和字典
要在遍历列表的同时对其进行修改,可使用while循环。通过将while循环同列表和字典结合起来使用,可收集、存储并组织大量输入,供以后查看和显示。
3.1 在列表之间移动元素
unconfirmed_users=["alice","brain","canda"]
confirmed_users=[]
while unconfirmed_users:
current_user=unconfirmed_users.pop()
print("Verifying user:"+current_user.title())
confirmed_users.append(current_user)
print(" The following users have been confirmed:")
for conformed_user in confirmed_users:
print(confirmed_user.title())
3.2 删除包含特定值的所有列表元素
使用函数remove()来删除列表中的特定值。
pets=["dog","cat","dog","fish","rabbit"]
while "cat" in pets:
pets.remove("cat")
print(pets)
3.3 使用用户输入来填充字典
responses={}
polling_active=True
while polling_active:
name=input(" What is your name?")
response=input(" Which mountain do you like?")
responses[name]=response
repeat=input("Would you like to tell others?(yes/no)")
if repeat=="no":
polling_active=False
print(" ----Poll Result---")
for name,response in responses.items():
print(name+"like to climb"+response+".")
在以上的学习中,我们得到知道:
(1)如何在程序中使用input()来让用户提供信息,如何处理文本和数字的输入
(2)如何使用while循环让程序按用户的要求不断地运行,如何设置标志、使用break语句以及使用continue语句等。