Python学习笔记(六)——用户输入和while循环

一 函数input的工作原理

函数input()让程序暂停允许,等待用户输入后,Python将其存储在一个变量中。例如:

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

函数input()结束一个参数:即要向用户显示的提示或说明。

1.编写清晰的程序

每次使用函数input时,都应该给出清晰易于明白的提示,准确告诉用户需要提供什么信息。例如:

name = input("Please tell me your name:")
print("Hello "+name)

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

使用函数input()时,Python将用户输入解读为字符串。当我们需要使用到数字时,需要使用到int(),int()可以将字符串转化为数字。例如:

height = input("How tall are you,in inches?\n")
height = int(height)
if height >= 36:
    print("yuu are tall enough to ride")
else:
    print("yuu are not tall enough to ride")

3.求模运算符

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

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

二 while循环简介

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

1.使用while循环

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

当定义的变量大于5时,此时程序会停止

2.让用户选择何时退出

可使用while循环在特定时不断循环,如下列程序,在用户输入退出值前,程序不会退出。

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

我们可以利用if修改,不将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)

3.使用标志

我们可以定义一个变量,用于判断整个程序是否处于活动状态。这个变量被称为标志:

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)

这样可以简化while循环,因为while循环不用跟任何值作比较。

4.使用break退出循环

如果达到条件后不需要执行别的程序了,只需要使用break退出程序:

prompt = "\nTell me something, and I will repeat it back to you~"
prompt += "\nEnter 'quit' to end the program: "

while True:
    message = input(prompt)
    if message == 'quit':
        break
    else:
        print(message)

5.在循环中使用continue

要返回到循环开头,并根据条件测试决定是否继续执行循环,可使用coutinue语句,它不像break一样直接退出程序:

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

这样可以输出10以内奇数

6.避免无限循环

编写循环程序时一定要有停止循环的途径,避免发生无限循环。

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

for循环是一种遍历列表的有效方式,但在for循环中不宜修改列表。要在遍历列表时同时修改它,可以使用到while循环。

1.在列表间移动元素

例如,此时有两个列表,我们需要在两个列表间移动元素。

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

while unconfirmed_users :
    confirmed_user = unconfirmed_users.pop()
    print("Verifing user:" + confirmed_user)
    confirmed_users.append(confirmed_user)
for confirmed_user in sorted(confirmed_users):
    print(confirmed_user.title())

此时,利用while循环将程序中的元素在列表中转移。

2.删除特定值的所有列表元素

我们可以使用remove()函数来删除列表中的元素。如:

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

3.使用用户输入来填充字典

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) ")
    if repeat == 'no':
        active = False

for x,y in responses.items():
    print(x+":"+y)

此程序先是先定义了一个空字典,并设置了一个标志,用与确定调查是否继续。在这个循环中,我们将用户的信息收集在response中,然后再name与resposes形成键值对。

猜你喜欢

转载自blog.csdn.net/weixin_51871724/article/details/121031369
今日推荐