python第七章——用户输入和while循环

论坛 期权论坛 编程之家     
选择匿名的用户   2021-6-2 16:52   672   0

7.1 函数input() 的工作原理

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

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

下面这个示例演示了一种创建多行字符串的方式

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("\nHello, " + name + "!")

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

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

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

if height>=36:
 print("\nYou're tall enough to ride")
else:
 print("\nYou will be able to ride when you're a little order")

7.1.3 求模运算符%

判断奇偶数

number=input("Enter a number ,and I will 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 在Python 2.7中获取输入

如果你使用的是Python 2.7,应使用函数raw_input() 来提示用户输入。这个函数与Python 3中的input() 一样,也将输入解读为字符串。 Python 2.7也包含函数input() ,但它将用户输入解读为Python代码,并尝试运行它们。因此,最好的结果是出现错误,指出Python不明白输入的代码;而最糟的结果是,将运行 你原本无意运行的代码。如果你使用的是Python 2.7,请使用raw_input() 而不是input() 来获取输入。

7.2 while 循环简介

一个简单的计数程序

current_number=1

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

7.2.2 让用户选择何时退出

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 使用break 退出循环

要立即退出while 循环,不再运行循环中余下的代码,也不管条件测试的结果如何,可使用break 语句。break 语句用于控制程序流程,可使用它来控制哪些代码行将执行, 哪些代码行不执行,从而让程序按你的要求执行你要执行的代码。

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

7.2.5 在循环中使用continue

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

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

我们首先将current_number 设置成了0,由于它小于10,Python进入while 循环。进入循环后,我们以步长1的方式往上数,因此current_number 为1。

接下来,if 语句检查current_number 与2的求模运算结果。如果结果为0(意味着current_number 可被2整除),就执行continue 语句,让Python忽略余下的代码,并返回到循环的开头。

如果当前的数字不能被2整除,就执行循环中余下的代码,Python将这个数字打印出来:

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

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

7.3.1 在列表之间移动元素

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

# -*- coding:utf-8 -*-
# 首先,创建一个待验证用户列表
# 和一个用于存储已验证用户的空列表
unconfirmed_users=['akashi','tsukishima','yamamoto']
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())

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

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

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

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

可使用while循环提示用户输入任意数量的信息。下面来创建一个调查程序,其中的循环每次执行时都提示输入被调查者的名字和回答。我们将收集的数据存储在一个字典中,以 便将回答同被调查者关联起来:

# -*- coding:utf-8 -*-
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 Result---")
for name,response in responses.items():
 print(name+" would like to climb "+response+".")

分享到 :
0 人收藏
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

积分:3875789
帖子:775174
精华:0
期权论坛 期权论坛
发布
内容

下载期权论坛手机APP