第七章 用户输入和 while 循环

7.1 函数 input() 的工作原理

函数 input() 有一个参数,该参数可以显示给用户,用来提示;函数 input()会 让程序暂停运行,等待用户输入一些文本

message = input("Tell me something, and I will repeat it back to you:")
print(message)
'''
如果输入:Hello, everyone!
屏幕也会显示:Hello, everyone!
'''

7.1.1 编写清晰的程序

关于函数input()的提示信息建议

  1. 提示末尾包含一个空格,这样提示信息和用户输入就分开了
  2. 如果提示信息过于复杂,可以用一个变量传递
prompt = "If you tell us who are you,we can personalize the message you see."
prompt += "\nWhat's your first name? "

name = input(prompt)
print(f"\nHello, {name}!")
'''
代码执行如下:
If you tell us who are you,we can personalize the message you see.
What's your first name? zhang xy

Hello, zhang xy!

'''

7.1.2 使用 input() 来获取数值输入

使用函数 input() 时,用户输入被解析为字符串,如果想使用整数,可以使用函数 int() 进行转化

age = input("How old are you? ")
print(type(age))

age = int(age)
print(type(age))
'''
输出:
How old are you? 18
<class 'str'>
<class 'int'>

'''

7.1.3 求模运算符

% 两个数求模,返回余数,如:
4 % 3 返回 1

7.2 while 循环

for 和 while 语句都是循环,for 一般用于遍历, while 一般用于不断执行的情况,直到条件不满足为止

7.2.1 使用 while 循环

current_number = 1

while current_number <= 5:
    print(current_number)
    current_number += 1
'''
输出:
1
2
3
4
5

'''

7.2.2 让用户选择何时退出

在 while 循环中定义一个退出值,用来推出循环程序

prompt = "\nTell me something, and I will repeat it back to you:"
prompt += "\nEnter 'quit' to end the programe. "

message = ""
while message != 'quit':
    message = input(prompt)
    if message != 'quit':
        print(message)
'''
输出:
Tell me something, and I will repeat it back to you:
Enter 'quit' to end the programe. hello world
hello world

Tell me something, and I will repeat it back to you:
Enter 'quit' to end the programe. 123
123

Tell me something, and I will repeat it back to you:
Enter 'quit' to end the programe. quit

'''

7.2.3 使用标志

如果退出条件不止一个,如果像上一个程序一样设置退出条件,就会让检查条件复杂且困难,此时可以使用标志位(标志位的检查和更改可以放在其它地方)

prompt = "\nTell me something, and I will repeat it back to you:"
prompt += "\nEnter 'quit' to end the programe. "

active = True
while active:
    message = input(prompt)
    if message == 'quit':
        active = False
    else:
        print(message)
'''
输出:

Tell me something, and I will repeat it back to you:
Enter 'quit' to end the programe. hello
hello

Tell me something, and I will repeat it back to you:
Enter 'quit' to end the programe. 123
123

Tell me something, and I will repeat it back to you:
Enter 'quit' to end the programe. quit

'''

7.2.4 使用 break 退出循环

使用 break 语句可以立即退出循环,不再执行循环中余下的所有代码

prompt = "\nTell me something, and I will repeat it back to you:"
prompt += "\nEnter 'quit' to end the programe. "

while True:
    message = input(prompt)
    if message == 'quit':
        break
    else:
        print(message)
'''
输出:

Tell me something, and I will repeat it back to you:
Enter 'quit' to end the programe. hello
hello

Tell me something, and I will repeat it back to you:
Enter 'quit' to end the programe. 123
123

Tell me something, and I will repeat it back to you:
Enter 'quit' to end the programe. quit

'''

7.2.5 在循环中使用continue 语句

continue 语句会退出本次循环,不再执行本次循环中余下的代码,注意与 break 语句区别

# 使用 continue 退出本次循环
current_number = 0

while current_number < 10:
    current_number += 1
    if current_number % 2 == 0:
        continue
    print(current_number)
'''
输出:
1
3
5
7
9

'''
# 使用 break 退出循环
current_number = 0

while current_number < 10:
    current_number += 1
    if current_number % 2 == 0:
        break
    print(current_number)
'''
输出:
1

'''

7.2.6 避免无限循环

while 循环必须要有明确的退出条件,不然程序就会无休止的执行下去

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

for 循环是一种遍历列表的有效方式,但不应在 for 循环中修改列表,否则将导致难以跟踪其中的元素;要在遍历列表的同时修改列表,可以使用 while 循环

7.3.1 在列表之间移动元素

一个列表中有新注册但未验证的用户,将用户验证后,移到已验证的用户列表中

unconfirmed_users = ['alice', 'brian', 'candace']
confirmed_users = []

while unconfirmed_users:
    confirmed_user = unconfirmed_users.pop()

    print(f"Verifying user:{confirmed_user.title()}")
    confirmed_users.append(confirmed_user)

print("\nThe following users have been confirmed:")
for confirmed_user in confirmed_users:
    print(confirmed_user.title())
'''
输出:
Verifying user:Candace
Verifying user:Brian
Verifying user:Alice

The following users have been confirmed:
Candace
Brian
Alice

'''

7.3.2 删除为特定值的所有列表元素

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']

'''

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

可以利用 while 循环,将某人说的话存储在字典中

responses = {}
polling_active = True

while polling_active:
    name = input("\nWhat's your name? ")
    response = input("What would you want to say? ")
    responses[name] = response # 将某人的话存储在字典中

    repeat = input("Any one else?('yes' or 'no') ")
    if repeat == 'no':
        polling_active = False

print(responses)
print(f"\n{'Poll Result':=^40}")
for name,response in responses.items():
    print(f"{name} says: {response}.")
'''
输出:

What's your name? zhang xy
What would you want to say? python would change world
Any one else?('yes' or 'no') yes

What's your name? mao
What would you want to say? good good study, day day up
Any one else?('yes' or 'no') no
{'zhang xy': 'python would change world', 'mao': 'good good study, day day up'}

==============Poll Result===============
zhang xy says: python would change world.
mao says: good good study, day day up.

'''

7.4 小结

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

张小勇zhangxy

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值