Python笔记-011-用户输入和while循环

1.11.1用户输入语句input()
input函数输入的时候,Python将用户输入觉都为字符串。一旦我们需要把输入当数字使用的时候,需要用到 例如:number=int(number) ,int()可以让python将输入视为数值。

number=input("Please input your name,I will tell you  if it is even or odd:")
number=int(number)

if number%2==0:
    print(str(number)+"  is a even ")
else :
    print(str(number)+" is a odd")

1) Please input your name,I will tell you if it is even or odd:4
4 is a even
2) Please input your name,I will tell you if it is even or odd:5
5 is a odd

一个会用到的运算符 %, 将两个数相处并返回余数

>>> 4%3
1

1.11.2 While 循环简介
while语句简单理解介绍:while不断循环,直到指定的条件不满足才会停止循环
1)用while循环

current_number=1
while current_number<=5:
    print(current_number)
    current_number+=1

1
2
3
4
5

2)让用户可以选择退出,记录一种使用标志位的方法

prompt="\nTell me somthing,and I will repeat it back to you "
prompt +="\n Enter 'quit' to end  the program."
active = True
while active:
      message = input(prompt)
      if message== 'quit':
         active=False
      else:
          print(message)

用户输入后if语句就会一直检查message的字符串,一旦对比是’quit’的时候,标志位active就变为 False,while active就不成立,循环结束,达到我们推出循环的效果。

3)使用break方法退出循环

prompt="\nTell me somthing,and I will repeat it back to you "
prompt +="\n Enter 'quit' to end  the program."
active = True
while active:
      message = input(prompt)
      if message== 'quit':
         # active=False
         break
      else:
          print(message)

经实验,我们可以直接用break直接跳出循环,注意:break跳出循环后不再执行余下的代码,跳出当前循环。2) 3)例程的效果一样。

4)在循环中使用continue

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

continue的作用是跳出当前的循环执行,跳到开头继续执行,从上述的程序我们可以看见 当是偶数的时候 print语句被continue跳出 忽略了。
E:\Python_Study\python_charm\venv\Scripts\python.exe E:/Python_Study/python_charm/pycharm_study.py
1
3
5
7
9

扫描二维码关注公众号,回复: 2868001 查看本文章

动手试一试
7-4 比萨配料:编写一个循环,提示用户输入一系列的比萨配料,并在用户输入quit时候结束,每当用户输入一组配料,都打印一条消息,说我们会在比萨增加这种配料。


prompt="\nYou ordered awith the following toppings: "
prompt +="\n Enter 'quit' to end  the program."
active=True
messages = []
while active:
       message=input(prompt)

       if message == 'quit':
                    break
       else:
        print("You have been added :")
        messages.append(message)
        print(messages)
        print("We will add the "+message+" in the pizza.")

自己在题目的基础上添加了打印已经添加的东西

7-5 电影票:有家电影院根据观众收取不同的票价:不到三岁的观众免费,3-12的观众为10,超过12岁的观众为15.请编写一个循环,在其中询问年龄,并且指出票价

prompt="\nHow old are you? Please enter your age : "
prompt +="\n Enter 'quit' to end  the program."
active = True
while active:
        age=input(prompt)
        if age == 'quit':
            break
        elif  int(age)<= 3 :
            print("You  are free,baby!")
        elif int(age)<12 :
            print("You should pay  10 dollar.")
        else:
            print("You should pay  15 dollar.")

E:\Python_Study\python_charm\venv\Scripts\python.exe E:/Python_Study/python_charm/pycharm_study.py

How old are you? Please enter your age :
Enter ‘quit’ to end the program.3
You are free,baby!

How old are you? Please enter your age :
Enter ‘quit’ to end the program.10
You should pay 10 dollar.

How old are you? Please enter your age :
Enter ‘quit’ to end the program.15
You should pay 15 dollar.

How old are you? Please enter your age :
Enter ‘quit’ to end the program.quit

Process finished with exit code 0

1.11.3 使用while循环来处理列表和字典
比如将将一个新注册但是未验证的网络用户列表。将他们添加到另一个已经验证的列表。

unconfirmed_users=['alice','brain','candance']
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())

Verifying user:Candance
Verifying user:Brain
Verifying user:Alice

The following users have been confirmed :
Candance
Brain
Alice

1.11.4 使用用户输入来填充字典

responses={}
polling_active=True
while polling_active:
     name= input("\n What 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':   #一旦检测到字符'no' 跳出循环,执行最后的打印信息
         polling_active=False
print("\n- - -   Poll Results - - -")
for name,response in responses.items():
    print(name+" would like to climb "+response+".")

What is your name ?Gonathan
Which mountain would you like to climb someday?FengHuang
Would you like to let another person respond ?(yes/no)no

      • Poll Results - - -
        Gonathan would like to climb FengHuang .

动手练一练
7-8 创建一个名为 sanwich_orders的列表,在其中包含各种三明治的名字,再创建一个名为finished_sandwiches的空列表,遍历列表sandwich_orders,对于其中的每种三明治,都打印一条小心,如 i made your tuna sandiwich 并将其移到列表 finished_sandwiches,所有三明治都能制作号,打印一条消息


sandwich_orders=["Tuna sandwich","Chicken sandwich","Mango sandwich"]
finished_sandwiches=[]
while sandwich_orders:
    finished=sandwich_orders.pop()
    print("I made your "+finished)
    finished_sandwiches.append(finished)

print("\n- - -   Poll Results - - -")
for finished_sandwich in finished_sandwiches:
    print(finished_sandwich)

I made your Mango sandwich
I made your Chicken sandwich
I made your Tuna sandwich

      • Poll Results - - -
        Mango sandwich
        Chicken sandwich
        Tuna sandwich

Process finished with exit code 0

猜你喜欢

转载自blog.csdn.net/qq_35989861/article/details/81808694