Python自动售货机程序问题:选品后价格无法输出求助
问题排查:Python自动售货机商品选择判断无输出
核心问题原因
input()函数获取用户输入时返回的是字符串类型,但你在判断条件中直接将其与整数(如1、2)比较,字符串和整数类型不匹配,导致所有判断条件都不成立,因此没有输出内容。
两种解决方法
方法1:将输入转换为整数
修改获取商品选择的代码,把输入转为整数类型:
purchase_choice = int(input()) print("Your enter is:", purchase_choice)
之后原有的整数判断逻辑可以保持不变。
方法2:将判断条件改为字符串匹配
保持输入为字符串,把判断条件中的整数改为对应的字符串:
else: if purchase_choice == '1': print("************ The item costs $1.00 ************") if purchase_choice == '2': print("************ The item costs $1.19 ************") if purchase_choice == '3': print("************ The item costs $1.50 ************") if purchase_choice == '4': print("************ The item costs $0.99 ************") if purchase_choice == '5': print("************ The item costs $1.99 ************")
额外优化建议
- 使用
elif替代多个独立if,减少不必要的判断:
else: if purchase_choice == '1': print("************ The item costs $1.00 ************") elif purchase_choice == '2': print("************ The item costs $1.19 ************") elif purchase_choice == '3': print("************ The item costs $1.50 ************") elif purchase_choice == '4': print("************ The item costs $0.99 ************") elif purchase_choice == '5': print("************ The item costs $1.99 ************") else: print("无效的商品编号,请重新输入")
- 利用已定义的商品字典动态输出价格,避免硬编码:
else: # 遍历商品列表匹配选择 for item in types: if item['type'] == purchase_choice: print(f"************ The item costs ${item['Price']:.2f} ************") break else: print("无效的商品编号,请重新输入")
- 增加输入合法性校验,防止用户输入非数字内容导致报错:
while True: purchase_choice = input() if purchase_choice.isdigit(): break print("请输入有效的数字编号") print("Your enter is:", purchase_choice)
内容的提问来源于stack exchange,提问作者adri
相关产品推荐
相关产品推荐

