用户输入和while循环

本文详细讲解了while循环的工作原理,包括如何结合input()获取用户输入、处理数值和求模运算,同时展示了如何在循环中控制流程、处理字典和列表,以及避免无限循环。实例涵盖用户交互、数据验证和列表操作技巧。
摘要由CSDN通过智能技术生成

目录

一、函数input( )工作原理

二、while循环简介

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


一、函数input( )工作原理

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

函数input( )接受一个参数(指要向用户显示的提示,让用户知道如何做)。python在运行第一行代码时,用户将看到提示Tell me something,and I will repeat it back to you:。程序等待用户输入,在用户按下回车键后继续运行。

>>> message = input("Tell me something,and I will repeat it back to you: ")
Tell me something,and I will repeat it back to you: Hello everyone!
>>> print(message)
Hello everyone!

注意:Sublime Text等众多编辑器不能运行提示用户输入的程序。可以使用Sublime Text来编写,但必须从终端运行

1.编写清晰的程序

使用input( )函数时,应指定清晰易懂的程序。

通过在提示末尾(冒号后)添加一个空格,可将提示与用户输入分开,让用户清楚的知道其输入始于何处。若提示超过一行,可将提示赋给一个变量,变量+=的方式在变量的末尾加一串字符串,再将该变量传递给函数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)   #终端上输入后,enter键就会打印下列提示
If you tell us who you are,we can personalize the messages you see.
What is your first name? Eric  #接着输入内容
>>> print(f"\nHello,{name}!")  #在终端上输入要打印的信息

Hello,Eric!

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

使用函数input( )时,python将用户输入解读为字符串,若只用来打印输入则毫无问题,但将输入作为数来使用,将会引发错误。

>>> age = input("How old are you? ")
How old are you? 21   #用户输入的是数字
>>> age
'21'                  #返回的是用户输入数字的字符串

无法将字符串和整数进行比较,会出现TypeError的错误。

>>> age = input("How old are you? ")
How old are you? 21
>>> age >= 18
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: '>=' not supported between instances of 'str' and 'int'

为解决这个问题,可使用函数int( ),将字符串转换成了数值表示。 

>>> age = input("How old are you? ")
How old are you? 21
>>> age = int(age)
>>> age >= 18
True

如何使用函数int( )?将数值输入用于计算和比较前,务必将其转为数值表示。

>>> height = input("How tall are you, in inches? ")
How tall are you, in inches? 71
>>> height = int(height)
>>> if height >= 48:
...     print("You are tall enough to ride!")  #记得按tab键
... else:
...     print("You'll be able to ride when you are a little older.")
...   #按两次回车才会出现结果
You are tall enough to ride!

注意在终端上操作if语句:if语句的下一行一定要按tab,不然会出现缩进错误IndentationError: expected an indented block。运行结果前按两次回车,结果就出现在再按一次回车后。

3.求模运算符(%)

求模运算符(%)是将两个数相除返回余数。不会指出一个数是另一个数的几倍,只指出余数是多少。可用被2除,余数是否为0,来判断是偶数还是基数。

>>> 4%3
1
>>> 6%2
0
>>> 8%3
2

可用被2除,余数是否为0,来判断是偶数还是奇数。 

>>> number = input("Enter a number,and I will tell you if it's even or odd: ")
Enter a number,and I will tell you if it's even or odd: 520
>>> number = int(number)
>>> if number %2 == 0:
...     print(f"The number {number} is even.")
... else:
...     print(f"The number {number} is odd.")
...
The number 520 is even.
>>>

二、while循环简介

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

1.使用while循环

 用while循环来数数。while = if + 其他 + for 

current_number = 1
while current_number <= 5: #只要current_number<=5,就接着运行这个循环
	print(current_number)
	current_number += 1    #current_number = current_number + 1的简写
1
2
3
4
5

2.让用户选择何时退出

 在while循环中定义了一个退出值,只要用户输出的不是这个数,程序就将接着运行。

python首次执行while语句时,需将message的值与‘quit’比较,但此时用户还未输入,若无可比较的东西,python将无法继续运行。故先指定初始值为空字符串。

input要放在循环中,不然不会重复输出,开头的提示信息可赋给一个变量。变量初始值设为空字符串,尽量只用两个变量。若只想执行一轮,可在while循环末尾加上break

>>> prompt = "Tell me something,and I will repeat it back to you:"
>>> prompt += "\nEnter 'quit' to end the program. "
#定义提示消息,告诉用户两个选择,要么输入一条消息,要么输入退出值
>>> message = ""    #将变量的初始值设为空字符串,使执行while循环时有可检查的东西
>>> while message != 'quit':
...     message = input(prompt)    #将显示提示消息和输入内容
...     print(message)
...
Tell me something,and I will repeat it back to you:
Enter 'quit' to end the program. Hello,everyone.
Hello,everyone.
Tell me something,and I will repeat it back to you:
Enter 'quit' to end the program. Hello,again.
Hello,again.
Tell me something,and I will repeat it back to you:
Enter 'quit' to end the program. quit
quit

这个程序将最后的quit也打印出来了,可添加if语句,使程序变完美。只打印输入不是quit的内容。

将变量初始值设为空字符串;循环,空字符串不等于quit,用户输入,比较;若输入quit,循环中第一轮就会停止,if后面的内容将不会继续。

>>> prompt = "Tell 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':      #只打印输入不是quit的内容
...             print(message)
...
Tell me something,and I will repeat it back to you:
Enter 'quit' to end the program. Hello,everyone.
Hello,everyone.
Tell me something,and I will repeat it back to you:
Enter 'quit' to end the program. Hello,again.
Hello,again.
Tell me something,and I will repeat it back to you:
Enter 'quit' to end the program. quit

3.使用标志(标志=True)

很多事情可能导致游戏的结束,如玩家失去了所有的飞船、时间已用完、保护的城市全部被毁。导致程序运行结束的事件有很多,若在一条while语句中检查所有这些条件,将复杂且困难。

要很多条件都满足才继续运行的程序中,可定义一个变量,用于判断整个程序是否处于活动状态。这个变量称为标志。充当程序的开关,标志=True时程序运行,标志=False=break语句关闭。

 while active:   如果标志变量为True,开始循环。

>>> prompt = "Tell me something,and I will repeat it back to you:"
>>> prompt += "\nEnter 'quit' to end the program. "
>>> active = True   #将标志变量设为True,使程序最初处于活动状态
>>> while active:   #如果标志变量为True循环就将继续
...     message = input(prompt)
...     if message == 'quit':
...             active = False    #如果输入为quit,标志变量改为False,程序停止运行
...     else:
...             print(message)
...
Tell me something,and I will repeat it back to you:
Enter 'quit' to end the program. Hello,everyone
Hello,everyone
Tell me something,and I will repeat it back to you:
Enter 'quit' to end the program. quit

4.使用break退出循环(while True打头)

要立即退出while循环,不运行余下代码,可使用break语句。break语句用于控制程序流程,可控哪些代码行执行,哪些不执行,让程序按你所想执行。

while True打头的循环将不断运行,直到遇到break语句。

>>> prompt = "Tell me something,and I will repeat it back to you:"
>>> prompt += "\nEnter 'quit' to end the program. "
>>> while True:     #以while True打头的循环将不断运行,直到遇到break语句。
...     city = input(prompt)
...     if city == 'quit':
...             break
...     else:
...             print(f"I'd love to go to the city {city.title()}.")
...
Tell me something,and I will repeat it back to you:
Enter 'quit' to end the program. hang zhou
I'd love to go to the city Hang Zhou.
Tell me something,and I will repeat it back to you:
Enter 'quit' to end the program. quit
>>>

5.在循环中使用continue

根据条件测试结果决定是否执行循环,可用continue语句。遇到continue语句,会返回开头的while循环

current_number = 0
while current_number < 10:
	current_number += 1
	if current_number % 2 == 0:  #如果为True,continue回到开头的while循环
		continue                
	print(current_number)        #如果为False,直接打印
1
3
5
7
9

6.避免无限循环

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

counting = 1
while counting <= 5:
	print(counting)
	counting += 1
1
2
3
4
5

若遗漏了代码行counting += 1,循环将没完没了的进行下去。

若程序陷入了无限循环,可按ctrl + C,也可关闭显示程序输出的终端窗口。Sublime Text等一些编辑器内嵌了输出窗口,导致难以结束无限循环,要关闭编辑器。

要避免编写无限循环,务必对每个while循环进行测试。确认程序至少有一个地方能让循环条件为False,或者让break语句得以执行。

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

for循环时遍历列表的有效方式,但在for循环中修改列表,会导致python难以跟踪其中的元素。在遍历列表的同时对其进行修改,可使用while循环。

1.在列表之间移动元素

从一个列表中提取(方法pop),再加入另一个空列表(方法append),最后遍历(for)

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)     #在用append方法时,不需要再赋给变量,只需要在变量后直接附加
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

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

用函数remove来删除列表中的特定值,之所以可行,是因为要删除的值在列表中只出现1次。若要删除列表中所有为特定值的元素,可用while循环+remove

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

3.使用用户输入来填充字典

可用while循环来提示用户输入任意多的信息,循环每次执行时都提示输入被调查者的名字和回答。先创建空字典,再循环添加键值对

while后面不能直接跟空列表或字典,可以跟标志变量active或者True。

>>> responses = {}
>>> polling_active = True
>>> while polling_active:     #注意这里是while active,而不是while responses。
...     name = input("What's your name? ")
...     response = input("Which mountain would you like to climb someday? ")
...     responses[name] = response    #添加键值对
...     repeat = input("Would you like to let another people respond?(yes/no) ")
...     if repeat == 'no':    #是否还需要继续调查
...             polling_active = False
...             print("---Poll Results---")
...     for name,response in responses.items():
...             print(f"{name} would like to climb {response}.")
...
What's your name? Eric
Which mountain would you like to climb someday? Denali
Would you like to let another people respond?(yes/no) yes
Eric would like to climb Denali.
What's your name? Lynn
Which mountain would you like to climb someday? Devil's Thu
Would you like to let another people respond?(yes/no) no
---Poll Results---
Eric would like to climb Denali.
Lynn would like to climb Devil's Thu.

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值