Python编程:从入门到实践(七)

用户输入和while循环

一、函数input的工作原理

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

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

输出:

Tell me something, I will repeat it back to you: Hello python!
Hello python!
编写清晰的程序

当提示超过一行时:

prompt = "If you tell us who you are, we can personalize the messages you see."
prompt += "\nWhat is your first name? "
message = input(prompt)
print(message)

输出:

If you tell us who you are, we can personalize the messages you see.
What is your first name? Liu
Liu
使用int()来获取数值输入
age = input("How old are you? ")
print(age >= 18)

此时会提示:

TypeError: '>=' not supported between instances of 'str' and 'int'

因为请求Python提供变量age的值时,它返回的是‘21’——用户输入的数值的字符串表示,Python将输入解读成了字符串。
为了解决这个问题,可使用函数int(),它让Python将输入视为数值。
函数int()将数字的字符串转换为数值表示。

age = input("How old are you? ")
age = int(age)
print(age >= 18)

输出:

How old are you? 20
True
求模运算符

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

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: 30

The number 30 is even.

二、while循环简介

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

使用while循环
current_number = 1
while current_number <= 5:
    print(current_number)
    current_number += 1

输出:

1
2
3
4
5
让用户选择何时退出
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)
    else:
        print("Program Quit!")

输出:


Tell me something, and I will repeat it back to you:
Enter 'quit' to end the program. Hello
Hello

Tell me something, and I will repeat it back to you:
Enter 'quit' to end the program. Bye
Bye

Tell me something, and I will repeat it back to you:
Enter 'quit' to end the program. quit
Program Quit!
使用标志

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

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
        print("Program Quit!")
    else: 
        print(message)

输出:


Tell me something, and I will repeat it back to you:
Enter 'quit' to end the program. Hello
Hello

Tell me something, and I will repeat it back to you:
Enter 'quit' to end the program. Bye
Bye

Tell me something, and I will repeat it back to you:
Enter 'quit' to end the program. quit
Program Quit!
使用break退出循环

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

prompt = "\nPlease enter the name of city you have visited: "
prompt += "\n(Enter 'quit' when you finished.)"
while True:
    message = input(prompt)
    if message != 'quit':
        print("I'd love to go to " + message)
    else:
        print("Program Quit!")
        break

输出:


Please enter the name of city you have visited: 
(Enter 'quit' when you finished.)Changsha
I'd love to go to Changsha

Please enter the name of city you have visited: 
(Enter 'quit' when you finished.)Beijing
I'd love to go to Beijing

Please enter the name of city you have visited: 
(Enter 'quit' when you finished.)quit
Program Quit!
在循环中使用continue

要返回到循环开头,并根据条件测试结果决定是否继续执行循环,可使用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
避免无限循环

如果程序陷入无限循环,可按Ctrl + C,也可关闭显示程序输出的终端窗口。
要避免编写无限循环,务必对每个while循环进行测试,确保它按预期那样结束。

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

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

在列表之间移动元素

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

unconfirmed_users = ['alien', 'brian', 'candace']
confirmed_users = []
while unconfirmed_users:
    current_user = unconfirmed_users.pop() #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: Alien

The following users have been confirmed:
Candace
Brian
Alien
删除包含特定值的所有列表元素

函数remove()来删除列表中的特定值,是因为要删除的值在列表中只出现了一次。
假设有一个宠物列表,其中包含多个值为’cat’的元素。要删除所有这些元素,可不断运行一个while循环,直到列表中不再包含值’cat’。

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']
使用用户输入来填充字典

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

responses = {}
active = True
while 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) ")
    while repeat != 'no' and repeat != 'yes':
        repeat = input("Would you like to let another person respond? (yes/ no) ")
    if repeat == 'no':
            active = False
print("\n--- Poll Results ---")
for name, response in responses.items():
    print(name + "would like to climb " + response + ".")

输出:


What is your name? 1
Which mountain would you like to climb someday? 1
Would you like to let another person respond? (yes/ no) yes

What is your name? 2
Which mountain would you like to climb someday? 2
Would you like to let another person respond? (yes/ no) haode
Would you like to let another person respond? (yes/ no) buhao
Would you like to let another person respond? (yes/ no) yes

What is your name? 3
Which mountain would you like to climb someday? 3
Would you like to let another person respond? (yes/ no) no

--- Poll Results ---
1would like to climb 1.
2would like to climb 2.
3would like to climb 3.
发布了22 篇原创文章 · 获赞 0 · 访问量 617

猜你喜欢

转载自blog.csdn.net/weixin_45237889/article/details/104026166