Python 用户输入和while循环

7.1 函数input()的工作原理

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

函数input()接受一个参数,程序运行时会等待用户输入,并在用户按回车键后继续运行。输入被赋给变量message,接下来的print(message)将输入呈现给用户。

7.1.1编写清晰的程序

name = input("Please enter your name:")
print(f"\nHello,{name}")

有时候,程序可能超过一行。在这种情况下,可将提示赋给一个变量,再将该变量传递给函数input()。、

prompt = "If you tell us who you are,we can .........."
prompt += "\nWhat is your first name?"
name = input(prompt)
print(f"\nHello,{name}")

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

使用函数input()时,Python将用户输入解读为字符串

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

How old are you?15
Traceback (most recent call last):
  File "C:/Users/Administrator/PycharmProjects/pythonProject/main.py", line 225, in <module>
    age >= 18
TypeError: '>=' not supported between instances of 'str' and 'int'

未解决这个问题,可使用函数int(),它让Python将输入视为数值。函数int()将数的字符串转换为数值表示。

print(f"\nHello,{name}")
age = input("How old are you?")
age = int(age)
print(age >= 18)

How old are you?12
False

7.1.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(f"\nThe number {number} is even")
else:
    print(f"\nThe number {number} is odd")

7.2while循环简介

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

7.2.1使用while循环

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

7.2.2让用户选择何时退出

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)

7.2.3使用标志

active = True
while active:
    message = input(prompt)
    if message == "quit":
        active = False
    else:
        print(message)

7.2.4使用break退出循环

prompt = "\nPlease enter the name of a city you have visited:"
prompt += "\nEnter 'quit' when you are finished."
while True:
    city = input(prompt)
    if city == "quit":
        break
    else:
        print(f"I'd love to go to {city.title()}!")

7.2.5在循环中使用continue

例如,来看一个从1数到10但只打印其中奇数的循环

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

7.2.6避免无限循环

下面的循环从1数到5

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

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

7.3.1在列表之间移动元素

通常是通过创建一个空列表,然后用两个列表实现对用户信息的移动

unconfirmed_users = ["alice", "brian", "candace"]
conformed_users = []
while unconfirmed_users:
    current_user = unconfirmed_users.pop()
    print(f"Verifying user:{current_user}")
    conformed_users.append(current_user)

print("\nThe following users have been confirmed:")
for conformed_user in conformed_users:
    print(conformed_user.title())

7.3.2删除为特定值的所有列表元素

之前我们可以使用remove()删除列表中的特定值,但如果删除的元素值不止一次呢

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

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

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(f"{name} would like to climb {response}")

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值