用户输入和while循环

  • 1.用户输入
  • 1.1函数input()
  • 1.2函数int()获取数值输入
  • 1.3求模运算符(%)
  • 2. while循环简介
  • 2.1使用while循环
  • 2.2让用户选择何时退出(quit)
  • 2.3使用标志
  • 2.4使用break退出循环
  • 2.5在循环中使用continue
  • 2.6避免无限循环
  • 3.使用while循环处理列表和字典
  • 3.1在列表之间移动元素
  • 3.2删除包含特定值的所有列表元素
  • 3.3使用用户输入来填充字典


1.用户输入

1.1函数input()

函数input()让程序暂停运行,等待用户输入一些文本。获得用户输出后,Python将其存储在一个变量中。每当使用input()时,都应指定清晰而易于明白的提示。

name=input("Please enter your name: ")
print("Hello, "+ name + "!")
#Please enter your name: zhouqing
#Hello, zhouqing!


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 + "!")
#结果
If you tell us who you are, we can personalize the message you see.
What is your first name? zhou

Hello, zhou!

1.2函数int()获取数值输入

使用input()时,Python将用户输入解读为字符串。
int()将数字的字符串表示转化为数值表示。

age=input("How old are you? ")
age=int(age)
age>=18
#How old are you? 12
#Out[3]: False

1.3求模运算符(%)

求模运算符(%),将两个数相除并返回余数。可以利用这一点来判断一个数是奇数还是偶数。

4%3
#1

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.")    

#Enter a number, and I'll tell you if it's even or odd: 5

#The number 5 is odd.

2. while循环简介

for循环用于针对集合中的每个元素的一个代码块
while循环不断地运行,知道指定的条件不满足为止。

2.1使用while循环

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

2.2让用户选择何时退出(quit)

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)   #缩进非常重要
#Tell me something, and i will repeat it back to you:
#Enter 'quit' to end the program. quit

2.3使用标志

在复杂事件中,很多不同的事件都导致程序停止运行,可以定义一个变量,用于判断整个程序是否处于活动状态。这个变量称之为标志。while只需要检查一个条件——标志的当前值是否为True。

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)
#Tell me something, and i will repeat it back to you:
#Enter 'quit' to end the program. hi
#hi

2.4使用break退出循环

要立即退出while循环,不再运行循环中余下的代码,也不管条件测试的结果如何,可执行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() + "!")

Please enter the name of a city you have visited:
(Enter 'quit' when you are finished.)changzhou
I'd love to go to Changzhou!

2.5在循环中使用continue

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

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

2.6避免无限循环

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

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

for循环是一种遍历列表的有效方式,但在for循环中不应修改列表。要在遍历列表的同时对其进行修改,可使用while循环。通过将while循环同列表和字典结合起来使用,可收集存储并组织大量输出。

3.1在列表之间移动元素

pop() 删除后保存在一个变量里

# 首先,创建一个待验证用户列表
# 和一个用于存储已验证用户的空列表
uncomfirmed_users = ['alice','brian','candace']
confirmed_users = []

#验证每个用户,直到没有未验证用户为止
# 将每个经过验证的用户都移到已验证用户列表中
while uncomfirmed_users:
    current_user = uncomfirmed_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())
#结果
Verifying user: Candace
Verifying user: Brian
Verifying user: Alice

The following users have been confirmed:
Candace
Brian
Alice

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

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.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, response in responses.items():
    print(name + " would like to climb " + response + ".")
    
#What is your name? zhouqing

#Which mountain would you like to climb someday? huangshan

#Would you like to let another person respond? (yes/no) no

#    ---Poll Results---
#zhouqing would like to climb huangshan.