用户输入和while循环

第6节.用户输入和while循环

6.1函数input()

简单的输入

massage=input("Tell me something,and I will repeat it back to you:")
print(massage)

输入数值

age=input("How old are you?")
print(age)
#此时用户输入会被默认解释为字符串

age=input("How old are you?")
age=int(age)
#此时就将用户输入指定成了数值
print(age)

#更加简便的指定用户输入
age=int(input("How old are you?"))
print(int(age))

6.2求模运算符

A=4%3
print(A)
#将两个数相除并返回余数

6.3while循环

while循环简介

current_number=1
while current_number<=5:   #循环从1数到5
   print(current_number)
   current_number +=1

让用户选择何时退出

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)

上述代码的缺点是将quit也打印了出来,下面用一个if语句优化它

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)

使用标志

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)

使用break函数退出循环

prompt="\nTell me something, and I will repeat it back to you:"
prompt+="\nEnter 'quit' to end the program. "
while True:
   city=input(prompt)
   if city == 'quit':
       break
       #break语句也可以用于退出遍历列表或字典的for循环
       else:
           print(f"I'd love to go to {city.title()}")

在循环中使用continue

current_number=0
while current_number <10:
   current_number += 1
   if current_number%2==0:
       continue
   print(current_number)

当程序陷入无限循环时,按CTRL+C可以关闭程序

6.4使用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 = ['dog', 'cat', 'dog', 'goldfish', 'cat', 'rabbit', 'cat']
print(pets)
while 'cat' in pets:
   pets.remove('cat')
print(pets)

使用用户输入来填充字典

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 respond? (yes/ no) ")
   if repeat == 'no':
       polling_active = False

#调查结束,显示结果
print("\n--- Poll Results ---")
for name, response in responses.items():
   print(name + " would like to climb " + response + ".")

 

posted @ 2021-11-16 10:23  仓颉cahr  阅读(55)  评论(0编辑  收藏  举报