Python如何使用元组配合循环逐索引相乘实现钞票总金额统计
问题根源
你现有代码的错误来源于嵌套循环的逻辑:每输入一种面值的持有数量,就会遍历全部面值乘该数量累加,相当于把单种面值的数量重复计算了6次,最终结果肯定不对。你不需要嵌套循环,只要让面值和对应的提示语一一配对遍历即可。
实现方案
用Python内置的zip()函数就可以把两个等长的元组按位置配对,一次循环同时取出对应的面值和提示语,完成计算:
total = 0 # 按从大到小顺序定义面值 values = (100, 50, 20, 10, 5, 1) # 顺序和面值完全对应,保证配对正确 prompts = ( "How many hundred dollar bills do you have? ", "How many fifty dollar bills do you have? ", "How many twenty dollar bills do you have? ", "How many ten dollar bills do you have? ", "How many five dollar bills do you have? ", "How many one dollar bills do you have? " ) # 同时遍历配对的面值和提示语 for value, prompt in zip(values, prompts): count = int(input(prompt)) total += value * count print(f"You have a total of ${total}, don't spend it all!")
进阶优化版本
你还可以进一步省略手动写提示语的步骤,直接根据面值自动生成提示文本,连第二个元组都不用定义,代码更简洁:
# 定义面值和对应的英文名称映射 bill_names = { 100: "hundred", 50: "fifty", 20: "twenty", 10: "ten", 5: "five", 1: "one" } total = 0 for value, name in bill_names.items(): count = int(input(f"How many {name} dollar bills do you have? ")) total += value * count print(f"You have a total of ${total}, don't spend it all!")
内容的提问来源于stack exchange,提问作者Carson Quinn
相关产品推荐
相关产品推荐

