侧边栏壁纸
博主头像
路小飞博主等级

行动起来,活在当下

  • 累计撰写 72 篇文章
  • 累计创建 12 个标签
  • 累计收到 0 条评论

目 录CONTENT

文章目录

7 用户输入和while循环

路小飞
2025-09-22 / 0 评论 / 0 点赞 / 2 阅读 / 4011 字

7.1 函数 input() 的工作原理

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

函数有一个参数,即提示用户输入内容的提示词,让用户知道要做什么。

while 'True':
    promt = (
    "每当你使用函数 input() 时,"
    "都应指定清晰而易于明白的提示,"
    "准确指出你希望用户提供什么样的信息: "
    )
    msg = input(promt)
    if msg == 'quit':
        break
    else:
        print(msg)

注意事项:

  • 每当你使用函数 input() 时,都应指定清晰而易于明白的提示,准确指出你希望用户提供什么样的信息;

  • 通过在提示末词末尾包含一个空格,可将提示词与用户输入分隔开;

  • 有时候,提示词可能超过一行,可将提示词存储到一个变量中,再将变量作为参数传递给 函数input();

  • 多行文本的变量值可以使用括号拆分为显示上的多行。

使用 input() 函数时,Python 将用户输入解读为字符串,此时,可以使用 int() 函数将类型转化为数值,以进行比较或者计算。

age = int(input("please input your age: "))
if age >= 18:
    print("cheng nian")

7.2 while 循环

while 循环初步使用

for 循环用于针对集合中每一个元素都执行一个代码块,而 while 循环能不断运行,直至指定的条件不再满足要求。

使用while 循环打印出 10 以内的偶数。

数值运算符:

符号描述
*乘法
/除法
**乘方
//整除
%余数
number_1 = 0
while number_1 <= 10:
    if (number_1 % 2) == 0:
        print(number_1)
        number_1 = number_1 + 1
    else:
        number_1 = number_1 + 1

使用 break 退出循环

使用 continue 跳过本次循环

number_1 = 0 
while True:
    if number_1 == 4:
        number_1 = number_1 + 1
        continue
    elif number_1 == 9:
        break      
    else:
        print(number_1)
        number_1 = number_1 + 1
 # 运行后将输出
0
1
2
3
5
6
7
8

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

# 商品库存列表
products = [
    {"id": 1, "name": "笔记本电脑", "price": 5999, "stock": 10},
    {"id": 2, "name": "鼠标", "price": 99, "stock": 50},
    {"id": 3, "name": "键盘", "price": 199, "stock": 30},
    {"id": 4, "name": "显示器", "price": 1599, "stock": 15}
]

# 购物车列表
shopping_cart = []

# 使用while循环处理用户购物流程
is_shopping = True
while is_shopping:
    print("\n===== 商品列表 =====")
    # 遍历商品列表展示商品
    for product in products:
        print(f"{product['id']}. {product['name']} - ¥{product['price']} (库存: {product['stock']})")
    
    # 获取用户选择
    choice = input("\n请输入商品ID添加到购物车(输入0结束购物): ")
    
    if choice == '0':
        is_shopping = False
    else:
        try:
            product_id = int(choice)
            # 查找选中的商品
            selected = None
            for p in products:
                if p['id'] == product_id:
                    selected = p
                    break
            
            if selected and selected['stock'] > 0:
                # 添加到购物车
                shopping_cart.append(selected)
                # 减少库存
                selected['stock'] -= 1
                print(f"已将 {selected['name']} 添加到购物车")
            else:
                print("商品不存在或库存不足")
        except ValueError:
            print("请输入有效的数字")

# 显示购物车结果
print("\n===== 您的购物车 =====")
if shopping_cart:
    total = 0
    # 使用while循环遍历购物车
    i = 0
    while i < len(shopping_cart):
        item = shopping_cart[i]
        print(f"{i+1}. {item['name']} - ¥{item['price']}")
        total += item['price']
        i += 1
    print(f"\n总价: ¥{total}")
else:
    print("购物车是空的")

0

评论区