Python-While语句和循环

'''第 7 章 用户输入和while 循环

在本章中,你将学习如何接受用户输入,让程序能够对其进行处理。在程序需要一个名字时,

你需要提示用户输入该名字;程序需要一个名单时,你需要提示用户输入一系列名字。为此,你需

要使用函数input() 。

你还将学习如何让程序不断地运行,让用户能够根据需要输入信息,并在程序中使用这些信息。为此,你需要使用while 循环让程序不断地运行,直到指定的条件不

满足为止。

通过获取用户输入并学会控制程序的运行时间,可编写出交互式程序。'''

#函数input() 的工作原理

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

在一个变量中,以方便你使用。'''

'''函数input() 接受一个参数:即要向用户显示的提示 或说明,让用户知道该如何做'''

message=input("tell me something, andiwill repeat it back to you: ")

print(message)

name=input('pls enter your name: ')

print('\nHello, ' + name.title() + '!')

# ~ 创建多行字符串的方式

promt='if you tell us who you are, we can personalize the messages you see.'

promt+='\nwhat is your first name?'

mes=input(promt)

print('\nHello, ' +mes+ '!')

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

age=input('how old are you?')

print(age)

#函数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 few years later.")

# 求模运算符 % 它将两个数相除并返回余数

number=input("enter a number, andi'lltell 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;

car=input('what do you want to rent today?')

print('\nLet me seeif i can find ' + car + '.')

# 7-2

seats=input('\nhow many seats would you want to reserve?')

seats=int(seats)

if seats > 8:

print('\nsorry, it is not available now.\n')

else:

print("\nfor sure, I'll keep it for you.")

#7-3;

number=input('enter a number pls\n')

number=int(number)

if number % 10 == 0:

print('yes, it can be divided by 10.\n')

else:

print("sorry, it's not a number that can be divided by 10")

'''while 循环简介'''

number=1

while number

print(number)

number += 1

'''可使用while 循环让程序在用户愿意时不断地运行,如下面的程序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)

'''使用标志

在要求很多条件都满足才继续运行的程序中,可定义一个变量,用于判断整个程序是否处于活动

状态。这个变量被称为标志 ,充当了程序的交通信号灯。你可让程序在标志

为True 时继续运行,并在任何事件导致标志的值为False 时让程序停止运行。这样,在while

语句中就只需检查一个条件——标志的当前值是否为True ,并将所有测试(是

否发生了应将标志设置为False 的事件)都放在其他地方,从而让程序变得更为整洁。'''

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)

'''使用break 退出循环

以while True 打头的循环将不断运行,直到遇到break 语句。这个程序中的循环不断输入

用户到过的城市的名字,直到他输入'quit' 为止。用户输入'quit'

后,将执行break 语句,导致Python退出循环:'''

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() + "!")

'''在循环中使用continue

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

break 语句那样不再执行余下的代码并退出整个循环。例如,来看一个从1数

到10,但只打印其中偶数的循环:'''

current_number = 0

while current_number

current_number += 1

if current_number % 2 == 0:

continue

print(current_number)

#避免无限循环

x = 1

while x

print(x)

x+=1

#7-4

pi='Pls add your pizza top.\n '

pi+="Enter 'quit' when you are finished.\n"

while True:

pizza=input(pi)

if pizza != 'quit':

print("We'll add " + pizza + " to your pizza.\n")

else:

break

#7-5

ad="Pls enter your age, I'll tell you the ticket price of you: \n"

ad+= "\nEnter 'quit' when you are finished.\n"

while True:

age=input(ad)

if age =='quit':

break

age = int(age)

if age

print("There's a free ticket for you.")

elif age

print("you would need to pay $10.")

else:

print("ticket price is $15.")

#7-6

ad="Pls enter your age, I'll tell you the ticket price of you: \n"

ad+= "\nEnter 'quit' when you are finished.\n"

indi=True

while indi:

age=input(ad)

if age =='quit':

indi=False

break

age = int(age)

if age

print("There's a free ticket for you.")

elif age

print("you would need to pay $10.")

else:

print("ticket price is $15.")

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

# 在列表之间移动元素

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

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

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

# e.g

unconfirmed=['peter','jason','chloe']

confirmed=[]

while unconfirmed:

current=unconfirmed.pop()

print("verifying " + current.title())

confirmed.append(current)

print("\nthe following users have been confirmed:")

for ccc in confirmed:

print(ccc.title())

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

'''在第3章中,我们使用函数remove() 来删除列表中的特定值,这之所以可行,是因为要删除的

值在列表中只出现了一次。如果要删除列表中所有包含特定值的元素,该怎么办呢?

假设你有一个宠物列表,其中包含多个值为'cat' 的元素。要删除所有这些元素,可不断运行一个

while 循环,直到列表中不再包含值cat'''

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

print(pets)

while 'cat' in pets:

pets.remove('cat')

print(pets)

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

'''可使用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, response in responses.items():

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

#try

res={}

indi=True

while indi:

name=input("\nwhat's your name?")

question=input("where did you go last weekend?\n")

res[name]=question

repeat=input("\nwould you let to let another person to respond? (y/n)")

if repeat == 'n':

indi=False

print("\n---------- poll results ----------")

for key, values in res.items():

print(key.title() + " went " + values.title() + " last weekend." )

#task 7-8

'''

1. whilesandich, not while True

2.list can't be applied by title()'''

sandwich=['b','c','a']

finished=[]

while sandwich:

checked=sandwich.pop()

print("\nI made your " + checked.title() + '.')

finished.append(checked)

print("\nI check all sanwiches: ")

for sa in finished:

print(sa)

#7-9

sandwich=['b','c','a','b']

finished=[]

print("\nsorry, b is sold out.")

while 'b' in sandwich:

sandwich.remove('b')

print(sandwich)

#7-10

user={}

while True:

name=input("\nwhat's your name?")

place=input("if you could visit one place, where would you like to go? ")

user[name]=place

reask=input("anyone else wants to response? (yes/no)")

if reask != 'yes':

break

for k, v in user.items():

print("\n" + k.title() + ' wants to visit ' + v.title())

user={}

indi=True

while indi:

name=input("\nwhat's your name?")

place=input("if you could visit one place, where would you like to go? ")

user[name]=place

reask=input("anyone else wants to response? (yes/no)")

if reask != 'yes':

indi=False

for k, v in user.items():

print("\n" + k.title() + ' wants to visit ' + v.title())

user={}

indi=True

while indi:

name=input("\nwhat's your name?")

place=input("if you could visit one place, where would you like to go? ")

user[name]=place

reask=input("anyone else wants to response? (yes/no)")

if reask == 'no':

indi=False

for k, v in user.items():

print("\n" + k.title() + ' wants to visit ' + v.title())

''在本章中学习了:如何在程序中使用input() 来让用户提供信息;如何处理文本和数字输入,以及如何使用while 循环让程序按用户的要求不断地运行;多种控制while循环流程的方式:设置活动标志、使用break 语句以及使用continue 语句;如何使用while 循环在列表之间移动元素,以及如何从列表中删除所有包含特定值的元素;如何结合使用while 循环和字典。'''

  • 发表于:
  • 原文链接http://kuaibao.qq.com/s/20180506G1EU0200?refer=cp_1026
  • 腾讯「云+社区」是腾讯内容开放平台帐号(企鹅号)传播渠道之一,根据《腾讯内容开放平台服务协议》转载发布内容。
  • 如有侵权,请联系 yunjia_community@tencent.com 删除。

同媒体快讯

扫码关注云+社区

领取腾讯云代金券