Python 用户输入和while循环

文章详细介绍了Python中input()函数的工作原理,如何编写清晰的提示获取用户输入,以及如何结合while循环进行数值处理、条件判断和列表操作,包括使用int()转换输入、求模运算、while循环结构及其在处理列表和字典中的应用。

1. 函数input( )的工作原理

函数input( ) 让程序暂停运行,等待用户输入一些文本。获取用户输入后,python 将其赋给一个变量,以方便你使用。例如:

message = input("tell me something, and i will repeat it back to you")
print(message)

python 运行第一行代码时,用户将看到提示tell me something, and i will repeat it back to you,程序等待用户输入,并在用户按回车键后继续运行,输入的内容被赋给变量 message,接下来第二行代码负责打印变量。

1.1 编写清晰的程序

每当使用函数input( ) 时,都应指定清晰易懂的提示,准确的指出希望用户提供什么样的信息—指出用户应该输入何种信息的任何提示都行,如下所示:

name = input("please enter your name: ")
print(f"\nHello,{name}")

有时候提示可能超过一行。在这种情况下,可将提示赋给一个变量,再将该变量传递给函数 input( ) ,如下所示:

prompt = "if you tell us who you are,we can personalize the messages you see."
prompt +="\nwhat is your first name?"
name = input(prompt)
print(f"\nhello,{name}")

本例演示了一种创建多行字符串的方式,运算符+= 在赋给变量 prompt 的字符串末尾附加一个字符串。

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

使用函数 input( ) 时,python 将用户输入解读为字符串。如下所示:

age =input("how old are you? ")
print(type(age))
# 结果
how old are you? 21
<class 'str'>

如果只是想打印输出这也没有问题,但如果试图将输入作为数来使用,就会因为类型不同引发错误。为解决这个问题可使用函数int( ),它让 python 将输入视为数值。如下所示:

age = input("how old are you? ")
age = int(age)
print(type(age))
# 结果
how old are you? 21
<class 'int'>

1.3 求模运算符

处理数值信息时,求模运算符(%) 是个很有用的工具,它将两个数相除并返回余数:

print(4 % 3)
print(5 % 3)
print(6 % 3)
# 结果
1
2
0

求模运算符不会指出一个数是另一个数的多少倍,只指出余数是多少。

2. while循环简介

for 循环用于针对集合中的每个元素都执行一个代码块,而 while 循环则不断运行,直到指定的条件满足为止。

2.1 使用while循环

可使用 while 循环来数数。例如:

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

2.2 让用户选择何时退出

可以使用 while 循环程序在用户愿意时不断运行,如下面的程序所示:

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也作为一条消息打印了出来。可修复这种问题,如下所示:

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)

2.3 使用标志

在要求很多条件都满足才继续运行的程序中,可定义一个变量,用于判断整个程序是否处于活动状态。这个变量称为标志(flag),充当程序的交通信号灯。可以让程序在标志为 True 时继续运行,并在任何事件导致标志的值为 False 时让程序停止运行。这样,在 while 语句中就只需要检查一个条件:标志的当前值是否为 True,然后将所有其他测试都放在其他的地方,从而让程序更简洁。

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)

这个程序的输出与前一个示例相同。这个程序使用一个标志来指出程序是否处于活动状态。这样,如果要添加测试以检查是否发生了其他导致 active 变为 False 的事件就会很容易。在复杂的程序中,标志很有用。

2.4 使用break退出循环

要立即退出 while 循环,不再运行循环中余下的代码,也不管条件的测试结果如何,可使用break语句。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
    else:
        print(f"i'd love to go to {city.title()}")

注意: 在任何 python 循环中都可使用 break 语句。例如,可使用 break 语句来退出遍历列表或字典的 for 循环。

2.5 在循环中使用continue

要返回循环开头,并根据条件测试的结果决定是否继续执行循环,可使用continue语句,它不像 break 语句那样不再执行余下的代码并退出整个循环。例如:

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

2.6 避免无限循环

每个 while 循环都必须有停止运行的途径,这样才不会没完没了的执行下去:

x = 1
while x <= 5:
    print(x)

上述代码无法停止循环,因为条件测试始终为 True。
如果程序陷入无限循环,可按Ctrl+C,也可关闭显示程序输出的终端窗口。

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

到目前为止,我们每次都只处理了一项用户信息:获取用户的输入,再将输入打印出来或做出应答,程序再次运行时,获悉另一个输入值并作出响应。然而,要记录大量的用户和信息,需要在 while 循环中使用列表和字典。
for 循环是一种遍历列表的有效方式,但不应在for循环中修改列表,否则将导致 python 难以跟踪其中的元素。要在遍历列表的同时对其进行修改,可使用 while 循环,通过将 while 循环同列表和字典结合起来使用,可收集、储存并组织大量输入,供以后查看和显示。

3.1 在列表之间移动元素

假设有一个列表包含新注册但还未验证的网站用户。验证这些用户后,如何将他们移到另一个已验证用户列表中呢?一种办法是使用一个 while 循环,在验证用户的同时将其从未验证用户列表中提取出来,再将其加入另一个已验证用户列表中。

unconfirmed_users = ["alice","brian","candace"]
confirmed_users = [ ]
while unconfirmed_users:
    current_user = unconfirmed_users.pop()
    print(f"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())

pop( ) 以每次一个的方式从列表末尾删除元素。

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

在第2章中我们使用函数remove( ) 来删除列表中的特定值。这之所以可行,是因为要删除的值只在列表中出现一次,如果要删除列表中所有为特定值的元素,该怎么办呢?示例如下:

pets = ["dog","cat","dog","goldfish","cat","rabbit","cat"]
print(pets)
while "cat" in pets:
    pets.remove("cat")
print(pets)

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

可使用 while 循环提示用户输入任意多的信息。下面创建一个调查程序,其中的循环每次执行时都提示输入被调查者的名字和回答。

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,respone in responses.items():
    print(f"{name} would like to climb {response}")
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

Litle_Pudding

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

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

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

打赏作者

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

抵扣说明:

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

余额充值