欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

python——用户和while循环

程序员文章站 2024-03-15 14:45:23
...

第七章:用户和while循环

7.1 函数input的工作原理

# 函数input使程序暂停运行,等待用户输入一些文本。获取用户输入之后,python将其存储在一个变量之中。
# input()接受一个参数:要向用户显示的提示或说明,让用户了解该怎么做。
message = input("Tell me something, and i will repeat it back to you")
print(message)
Tell me something, and i will repeat it back to youhui
hui
# 对于以上问题,我们需要将字符串类型的变量转化为int。
age = input("Please input your age :")
age = int(age)
if age < 12:
    print("you are a child")
else:
    print("you are not a child")

Please input your age :15
you are not a child

7.2 while循环

# for循环用于针对集合中的每个元素都有一个代码块,而while循环不断地运行,直到指定的条件不再满足。
# 利用while循环数数
# 当数据大于10的时候,停止输出
current_number = 1
while current_number <= 10:
    print(current_number)
    current_number += 1
    
1
2
3
4
5
6
7
8
9
10
# 我们可以自定义何时退出循环
prompt = "Tell me something, and i will repeat it to you !"
prompt += "you can enter 'quit' to end the program"
message = ""
while message != 'quit':
    message = input(prompt)
    print(message)
Tell me something, and i will repeat it to you !you can enter 'quit' to end the programhui
hui
Tell me something, and i will repeat it to you !you can enter 'quit' to end the programquit
quit
# 使用break退出循环
# 要立即退出循环,不再运行循环中的代码,也不管测试的条件如何,可以使用break语句
prompt = "Please enter the name of a city that you have visited !"
prompt += "Enter 'quit' to end the program"
while True:
    city = input(prompt)
    if city == 'quit':
        break
    else:
        print("I would like to go to "+city+" !")
Please enter the name of a city that you have visited !Enter 'quit' to end the programhenan
I would like to go to henan !
Please enter the name of a city that you have visited !Enter 'quit' to end the programquit
# 若使程序返回到循环开头,并根据测试结果决定是否继续执行循环,可使用continue语句,它不像break语句不再执行余下的代码而是返回
#到循环开头
# 执行continue语句时,使代码返回到循环开头!!!
current_num = 0
while current_num < 10:
    current_num += 1
    if current_num % 2 ==0:
        continue
    print(current_num)
1
3
5
7
9
# 一定要避免无线循环!!
x = 1
while x < 10:
    print(x)
    x += 1
# 如果遗漏 x += 1,程序会进入无线循环
1
2
3
4
5
6
7
8
9

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

# for循环是一种遍历列表的有效方式,但是在for循环中不应修列表,否则将导致python难以跟踪其中的元素。
# 若需要在遍历列表的同时对列表进行修改,可以使用while循环
# 设存在一个列表,其中包含新注册的用户,验证这些用户,将其移到已验证的用户列表。
unconfirmed_users = ['alice', 'brian', 'candace']
confirmed_users = []
while unconfirmed_users:
    current_user = unconfirmed_users.pop()
    print("Verfying user:"+current_user.title())
    confirmed_users.append(current_user)
print("The following user has been confirmed:")
for user in confirmed_users:
    print(user.title())
Verfying user:Candace
Verfying user:Brian
Verfying user:Alice
The following user has been confirmed:
Candace
Brian
Alice
# remove()用来删除某个特定元素,但是如果该元素存在不止一次,就需要和while循环结合
# 删除包含特定值的所有列表元素
pets = ['dog', 'cat', 'dog', 'goldfish', 'cat', 'rabbit', 'cat']
print(pets)

while 'cat' in pets:
    pets.remove('cat')
print(pets)
['dog', 'cat', 'dog', 'goldfish', 'cat', 'rabbit', 'cat']
['dog', 'dog', 'goldfish', 'rabbit']
# 可使用while提示用户输入,并将用户的输入存储在一个字典中
responses= {}
polling_active = True
while polling_active:
    name = input("what is your name ? ")
    response = input("which mountain would you like to climb ?")
    responses[name] = response
    repeat = input("Would you like to let other person respond ? (yes / no)")
    if repeat == 'yes':
                 polling_active = True
    
print("\n--- poll result ---")
for name, response in responses.items():
                 print(name + " would like to climb " + response)
what is your name ? hui
which mountain would you like to climb ?yellow mountain
Would you like to let other person respond ? (yes / no)ji

--- poll result ---
hui would like to climb yellow mountain
# 梦想的度假胜地
# 编写一个程序,调查用户梦想的度假旅游胜地,并将调查结果打印显示
response = {}
polling_active = True
while polling_active:
    name = input("Can you tell me your name ?")
    place = input("Would you like tell me which place you want go ?")
    response[name] = place
    message = input("would you like another person answer this question ?(yes/no) ")
    if message == "yes":
        polling_active = True
    else:
        polling_active = False
        
for name, place in response.items():
    print(name+" would like to go "+place)
    
Can you tell me your name ?hui
Would you like tell me which place you want go ?beijing
would you like another person answer this question ?(yes/no) no
hui would like to go beijing

练习

1、餐馆订位:编写一个程序,询问多少人用餐,如果超过8人,打印一条消息指出没有空桌,否则指出有空桌!
2、电影票:有家电影院根据观众的年龄收取不同的票价;不到3岁的观众免费;3-12岁的观众10,美元;超过12岁的观众15美元。请编写一个循环,询问观众的年龄,并指出票价。
3、熟食店:创建一个名为sandwich_orders的列表,在其中包含各种三明治的名字;再创建一个名为finished_sandwiches的空列表。遍历列表sandwich_orders,对于每种三明治都打印出一条消息:如:I made your tuna sandwich.并将其移到列表finished_sandwiches。所有三明治都做好之后,打印一条消息,将这些三明治列出来。