Python编程 从入门到实践——第7章 用户输入和while循环

7,1 函数input()的工作原理

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

# parrot.py
# 函数input()接收一个参数——要向用户显示的提示或说明,让用户知道如何做
# 程序等待用户输入,并在用户按回车键后继续运行,输入被赋给变量message
message = input("Tell me something, and I will repeat it back to you: ")
print(message)

7.1.1 编写清晰的程序

# greeter.py
name = input("Please enter your name: ")
print(f"\nHello, {name}!")

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}!")

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

使用函数input()时,Python将用户输入解读为字符串。

>>> age = input('How old are you? ')
How old are you? 21
>>> age
'21'

# 函数int(),让Python将输入视为数值,将数的字符串表示转换为数值表示
>>> age = input('How old are you? ')
How old are you? 21
>>> age = int(age)
>>> age
21
# rollercoaster.py
height = input("How tall are you, in inches? ")
height = int(height)
if height >= 48:
	print("\nYou're tall enough to ride!")
else:
	print("\nYou'll be able to ride when you're a littler older")

7.1.3 求模运算符

求模运算符(%)将两个数相除并返回余数。

# even_or_odd.py
number = input("Enter a number, and I'll tell you if it's even or odd: ")
number = int(number)

if number % 2 == 0:
	print(f"\nThe number {number} is even.")
else:
	print(f"\nThe number {number} is odd.")

7.2 while循环简介

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

7.2.1 使用while循环

# counting.py
current_number = 1
while current_number <= 5:
	print(current_number)
	current_number += 1

7.2.2 让用户选择何时退出

# parrot.py
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)

7.2.3 使用标志

在要求很多条件都满足才继续运行的程序中,可定义一个变量,用于判断整个程序是否处于活动状态。这个变量称为标志。可以让程序在标志位True时继续运行,并在任何事件导致标志的值为False时让程序停止运行。

# parrot.py
promt = "\nTell me something, and I will repeat it back to you:"
promt += "\nEnter 'quit' to end the program."
active = True
while active:
	message = input(prompt)
	if message == 'quit':
		active = False
	else:
		print(message)

7.2.4 使用break退出循环

要立即退出while循环,不再运行循环中余下的代码,也不管条件测试的结果如何,可使用break语句。在任何Python循环中都可使用break语句。例如,可使用break语句来退出遍历列表和字典的for循环。

# cities.py
prompt = "\nPlease enter the name of a city you have visited:"
prompt += "\n(Enter 'quit' when you are finished.)"

while True:
	city = input(prompt)
	if city == 'quit':
		break
	else:
		print(f"I'd love to go to {city.title()}!")

7.2.5 在循环中使用continue

要返回循环开头,并根据条件测试结果决定是否继续执行循环,可使用continue语句。

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

7.2.6 避免无限循环

每个while循环都必须有停止运行的途径。如果程序陷入无限循环,可按Ctrl+C,也可关闭显示程序输出的终端窗口。

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

7.3.1 在列表之间移动元素

for循环是一种遍历列表的有效方式,但不应在for循环中修改列表,否则将导致Python难以跟踪其中的元素。要在遍历列表的同时对其进行修改,可使用while循环。通过将while循环同列表和字典结合起来使用,可收集、存储并组织大量输入,供以后查看和显示。

# confirmed_users.py
unconfirmed_users = ['alice', 'brian', 'candace']
confirmed_users = []

while unconfirmed_users:
    # 方法pop()以每次一个的方式从列表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())

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

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

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

# mountain_poll.py
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, response in responses.items():
	print(f"{name} woulf like to climb {response}.")

7.4 小结

在本章中,你学习了:如何在程序中使用input()来让用户提供信息;如何处理文本和数的输入,以及如何使用while循环让程序按用户的要求不断运行;多种控制while循环流程的方式:设置活动标志、使用break语句以及使用continue语句;如何使用while循环在列表之间移动元素,以及如何从列表中删除所有包含特定值的元素;如何结合使用while循环和字典。
在第8章中,你将学习函数。函数让你能够将程序分成很多个很小的部分,每部分都负责完成一项具体任务。你可以根据需要调用同一个函数人一次,还可将函数存储在独立的文件中。使用函数可让你编写的代码效率更高、更容易维护和排除故障,还可在众多不同的程序中重用。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值