python从入门到实践第七章_《Python编程:从入门到实践》 第九天

第七章 : 用户输入和While循环

这章主要学习while循环以及如何从用户那里获取输入。python

7.1 函数input()的工做原理

函数input()让程序暂停运行,等待用户输入一些文本。获取用户输入后,Python将其存储在一个变量中。web

message = input("Tell me something, and I will repeat it back to you: ")

print(message)

将输入存储在变量message中,而后将message打印出来让用户看到。在用户按回车键后继续运行。app

7.1.1 编写清晰的程序

每当你使用函数input()时,都应指定清晰而易于明白的提示,准确地指出你但愿用户提供什么样的信息。

1.能够在提示尾部包含一个空格,将提示与用户输入分开,让用户知道是从什么地方开始输入的。python2.7

name = input("Please enter your name: ")

print("Hello, " + name + "!")

2.有时候,提示可能超过一行,可将提示存储在一个变量中,再将该变量传递给input()。ide

prompt = "If you tell us who you are, we can personalize the message you see."

prompt += "\nWhat is your first name? "

name = input(prompt)

print("\nHello, " + name + "!")

这是一种建立多行字符串的方式。第一行前半部分在变量prompt中,第二行中,运算符+=在存储prompt中的字符串末尾附加一个字符串。svg

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

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

b3ac3a97c8416a706d1a7af89b90aebc.png

没法做为数值表示,特别是进行数值比较的时候:

1d230a8fff90d2db136b8e355c4ae166.png

为解决这个问题,可以使用函数int(),它让Python将输入视为数值。函数int()将数字的字符串表示转换为数值表示:

65c9a313856e46b8934109beb85bbccd.png

在实际程序中使用int()函数:函数

height = input("How tall are you, in inches? ")

height = int(height)

if height >= 36:

print("\nYou're tall enough to ride!")

else:

print("\nYou'll be able to ride when you're a little older.")

将数值输入用于计算和比较前,务必将其转换为数值表示。工具

7.1.3 求模运算符

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

求模运算符只返回余数,若是一个数能够被另一个数整除,余数为0,所以求模运算符返回0,能够用这个来判断这个数是奇数仍是偶数。学习

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

number = int(number)

if number % 2 == 0:

print("\nThe number " + str(number) + "is even.")

else:

print("\nThe number " + str(number) + " is odd. ")

7.1.4 在python2.7中获取输入

若是你使用的是Python 2.7,应使用函数raw_input()来提示用户输入。

Python 2.7也包含函数input(),但它将用户输入解读为Python代码,并尝试运行它们。测试

7.2 While循环简介

7.2.1 使用while循环

#使用while循环来数数,从1到5

current_number = 1

while current_number <= 5:

print(current_number)

current_number += 1

7.2.2 让用户选择什么时候退出

#让用户选择什么时候退出

prompt = "If you tell us who you are, and I will repeat it back to you: "

prompt += "\nEnter 'quit' to end the program. "

message = ""

while message != 'quit':

message = input(prompt)

print(message)

咱们将变量message的初始值设置为空字符串"",让Python首次执行while代码行时有

可供检查的东西。须要将message的值与’quit’进行比较,但此时用户尚未输入。虽然这个初始值只是一个空字符串,但符合要求,让Python可以执行while循环所需的比较。

#改进,不将'quit'打印出来

prompt = "If you tell us who you are, 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时让程序中止运行。这样,在while语句中就只需检查一个条件——标志的当前值是否为True,并将全部测试(是否发生了应将标志设置为False的事件)都放在其余地方,从而让程序变得更为整洁。

#咱们把这个标志命名为active(可给它指定任何名称),它将用于判断程序是否应继续运行:

prompt = "If you tell us who you are, 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)

7.2.4 使用break退出循环

要当即退出while循环,再也不运行循环中余下的代码,也无论条件测试的结果如何,可以使用break语句。

break语句用于控制程序流程,可以使用它来控制哪些代码行将执行,哪些代码行不执行,从而让程序按你的要求执行你要执行的代码。

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("I'd love to go to " + city.title() + "!")

在任何Python循环中均可使用break语句。例如,可以使用break语句来退出遍历列表或字典的for循环。

7.2.5 在循环中使用continue

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

# 从1数到10,可是只打印其中的偶数循环

current_number = 0

while current_number < 10:

current_number += 1

if current_number % 2 == 0:

continue

print(current_number)

执行continue语句,让Python忽略余下的代码。

7.2.6 避免无限循环

每一个while循环都必须有中止运行的途径。

若是程序陷入无限循环,可按Ctrl + C,也可关闭显示程序输出的终端窗口。

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

for循环是一种遍历列表的有效方式,但在for循环中不该修改列表,不然将致使Python难以跟踪其中的元素。要在遍历列表的同时对其进行修改,可以使用while循环。

7.3.1 在列表之间移动元素

# 首先,建立一个待验证用户列表

# 和一个用于存储已验证用户的空列表

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

confirmed_users = []

#验证每一个用户,直到没有未验证用户为止

#将每一个通过验证的列表都移到已验证用户列表中

while unconfirmed_users:

current_user = unconfirmed_users.pop()

print("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())

一种办法是使用一个while循环,在验证用户的同时将其从未验证用户列表中提取出来,再将其加入到另外一个已验证用户列表中。

7.3.2 删除包含特定值的全部列表元素

咱们前面用函数remove()来删除列表中的特定值这是只能用于要删除的值只在列表中出现了一次。

若是要删除列表中全部包含特定值的元素呢?

#删除‘cat’

pets = ['dog','cat','dog','goldfish','cat','rabbit','cat']

print(pets)

while 'cat' in pets:

pets.remove('cat')

print(pets)

7.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,responses in responses.items():

print(name + " would like to climb " + responses + ".")

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值