第7章 用户输入和while循环

第七章 用户输入和while循环

1.函数input()

input()

函数input()让程序暂停运行,等待用户输入一些文本。

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

name = input(prompt)
print(f"\nHello, {name}!")
使用int()来获取数值输入
>>> age = input("how old are you?")
how old are you?21
>>> age>= 18
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: '>=' not supported between instances of 'str' and 'int'

此处发生错误是因为将用户输入字符串’21’与数值18比较,因此需要将用户输入的字符串转换数字

int():将输入视为数值,将数的字符串表示转换为数值表示

>>> age = int(age)
>>> age>=18
True
求模运算符

2.while循环简介

让用户选择何时退出

通过设定退出值

使用标志

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

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)

使用break退出循环

break语句用于控制程序流程,可用来控制哪些代码行将执行、哪些代码行不执行,在任何python循环中都可以使用break语句

在循环中使用continue

要返回循环开头,并根据条件测试结果决定是否继续执行循环,可使用continue语句,忽略余下代码,并返回循环开头

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

前提:不应在for循环中修改列表,否则将导致python难以跟踪其中的元素,要在遍历列表的同时对其进行修改,可使用while循环,通过将while循环同列表和字典结合起来使用,可收集、存储并组织大量的输入,供以后查看和显示

在列表之间移动元素
unconfirmed_users = ['alice','brian','candace']
confirmed_users = []
while unconfirmed_users:
    current_user = unconfirmed_users.pop()#从末尾删除元素
    print(f"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())
删除为特定值的所有列表元素

while循环配合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(f"{name} would like to climb {response}.")
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

爱笑的刺猬

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值