Python-用户输入和while循环

用户输入和while循环

函数input()

函数input()让程序暂停运行 等待用户输入一些文本 并在用户按回车键之后继续运行

message=input("please")
print(message)

使用int()来获取数值输入

age=input("Houw old are you? ")
age=int(age)
if age>18:
  print("true")

当输入的为数字时 Python会认为是字符串 后续无法将字符串类型与整数类型比较 因此要转化成整数类型

求模运算符%

通俗来讲就是求余数

number=input("请输入数字 ")
number=int(number)
if number%10==0:
   print(str(number)+" 是偶数")
else:
   print(str(number)+" 不是偶数")

注意在将输入的字符串转化成整数比较之后 后续的输出又要用到所输入的字符串又将她转化成了字符串类型

while循环

for循环是用于针对集合中没一个元素的代码块while循环是不断地运行 知道指定的条件不满足为止

让用户选择何时退出

可以定义一个值 当用户输入的内容为这个值时 则退出循环

age="\n请输入你的年龄"
age+='\n您需要支付'
message=""
while message != 'quit':
   message=input(age)
   message=int(message)
   if message <3:
       print("free")
   elif message <13:
       print("10")
   elif message >12:
           print("15")

当用户输入quit时 循环会自动结束

使用标志

定义一个变量 用于判断整个程序是否处于活动状态 这个变量被称为标志

prompt="\n你想要什么披萨配料"
prompt+="\n我们会在披萨中添加"
message=""
active=True
while active:
   message=input(prompt)
   if message =="quit":
       active=False
   else:
       print(message)

首先我们将标志active设置成了True 让程序处于活动状态 当用户输入quit时 active将变为Flase 则循环将会停止

使用break退出循环

prompt="\n你想要什么披萨配料"
prompt+="\n我们会在披萨中添加"
message=""
while message != 'quit':
   message=input(prompt)
   if message =='quit':
       break
   else:
       print(message)

在循环中使用continue

当使用continue时 会跳过循环中剩下的代码 直接回到循环开头

number=0
while number < 10:
   number+=1
   if number%2==0:
       continue
   print(number)
结果:
1
3
5
7
9

使用while循环来处理列表和字典

在列表之间移动元素

sandwich_orders=['zhi shi','pei gen','huo tui']
finished_sandwiches=[]
while sandwich_orders:
   sandwich=sandwich_orders.pop()
   print("I made your "+sandwich.title()+"sandwich")
   finished_sandwiches.append(sandwich)
print(finished_sandwiches)

pop():移除列表中的值并返回该元素(默认最后一个元素)

删除包含特定值的所有列表元素

sandwich_orders=['zhi shi','pei gen','pastrami','huo tui']
finished_sandwiches=[]
print("pastrami is sell out")
while 'pastrami' in sandwich_orders:
   sandwich_orders.remove('pastrami')

这里避免列表中含有多个特定值 故使用while循环 知道特定值全部移除 则循环消失

使用用户输入来填充字典

holiday_resorts={}
polling=True
while polling:
   name=input("\n请输入你的姓名:")
   holiday_resort=input("\nIf you could visit one place in the world,where would you go?")
   holiday_resorts[name] = holiday_resort
   repect=input("\nWould you like to let another person respond? (yes/no)")
   if repect=='no':
       polling=False
for names,position in holiday_resorts.items():
   print(name+"想要去"+position)



posted @ 2020-08-06 15:45  厄文  阅读(395)  评论(0)    收藏  举报