Python学习笔记6(函数input和while循环)

本文深入讲解了Python中的函数input和while循环的使用方法,包括如何获取用户输入、使用while循环进行重复操作,以及如何结合列表和字典进行数据处理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

第六章 函数input和while循环

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

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

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

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

输出:1
2
3
4
5

6.2.1 让用户选择何时退出

prompt = "Tell me something, and i will repeat it back to you:"
prompt += "Enter 'quit' to end the program."
while message != 'quit':
    message = input(prompt)
    if message = 'quit':
        print(message)

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

prompt = "Tell me something, and i will repeat it back to you:"
prompt += "Enter 'quit' to end the program."
activate = True #设置标志
while activate: #根据标志的状态来决定运行或停止
    message = input(prompt)
    if message = 'quit':
        #如果用户输入的内容为quit,那么标志就变为Fasle
        activate = False
    else:
        print(message)    

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

prompt = "Please enter your live city:"
prompt += "(Enter 'quit' when you are finished.)"
while True:
    # 以while True打头的循环将不断运行
    city = input(prompt)
    if city == 'quit':
        break
    else:
    print(city.title())    

6.2.4 使用continue
要返回到循环开头,并根据条件测试结果决定是否继续执行循环,可使用continue语句。

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

6.3 使用while循环来处理列表和字典
6.3.1 在列表之间移动元素

# 存储待验证用户
unconfirmed_users = ['chen', 'zed', 'maxin']
# 存储已验证用户
confirmed_users = []

while unconfirmed_users:
    # 一直循环直到unconfirmed_users中没有元素

    # 将待验证用户从末尾一个一个删除,并存储进变量中
    current_user = unconfirmed_users.pop()
    # 将验证过的用户添加到已验证用户的列表中
    confirmed_users.append(current_user)

# 显示已验证的用户
for confirmed_user in confirmed_users:
    print(confirmed_user.title())

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

pets = ['cat', 'dog', 'duck', 'duck', 'fish', 'duck']

while 'duck' in pets:
    # 只要列表pets中还有duck元素,while循环就一直运行,直到列表中没有duck元素
    pets.remove('duck')
print(pets)

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

users = {}
# 设置标志
activate = True

while activate:
    name = input("你的名字叫什么?")
    hobby = input("你的爱好是什么?")

    # 将用户回答的内容添加进字典
    users[name] = hobby

    repeat = input("还有人要参加调查吗?yes/no")
    if repeat == 'no':
        activate = False
# 显示调查结果
for name, hobby in users.items():
    print(name + "的爱好是:" + hobby)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

天意不可违.

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

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

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

打赏作者

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

抵扣说明:

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

余额充值