Python学习笔记--用户输入和while 循环

函数input() 的工作原理

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

在这个示例中,Python运行第1行代码时,用户将看到提示Tell me something, and I will repeat it back to you: 。程序等待用户输入,并在用户按回车键后继续运行。输入存储在变量message 中,接下来的print(message) 将输入呈现给用 户。有时候,提示可能超过一行,例如,你可能需要指出获取特定输入的原因。在这种情况下,可将提示存储在一个变量中,再将该变量传递给函数input() 。

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

使用函数input() 时,Python将用户输入解读为字符串。如果你试图将输入作为数字使用,就会引发错误。为解决这个问题,可使用函数int() ,它让Python将输入视为数值。函数int() 将数字的字符串表示转换为数值表示。

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

while 循环简介

while 循环不断地运行,直到指定的条件不满足为止。

使用while 循环

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

让用户选择何时退出

message = "" 
while message != 'quit':
    message = input(prompt)
    print(message)

使用break 退出循环

while True:
    city = input("输入")
    if city == 'quit':
        break
    else:
        print("I'd love to go to " + city.title() + "!")

在循环中使用continue

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

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

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

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

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

使用用户输入来填充字典

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

猜你喜欢

转载自blog.csdn.net/PRCORANGE/article/details/107703460