我的自动售货机程序在将所有元素附加到列表之后未打印列表中的所有元素。例如:


费用是50便士。
插入量为62p
它应该返回:['10p'],['2p']
但只会返回:['10p']


感谢您提供的任何帮助,也感谢您提供的任何改进我的代码的帮助,我是编程新手!

prompt_cost = int(input("What are the total cost in pence? "))
prompt_insert_money = int(input("Insert the amount of pence (max 100p) into the machine: "))
coins = ["50p", "20p", "10p", "5p", "2p", "1p", "0p"]
list = []

for coin in coins:
    pence_change = prompt_insert_money - prompt_cost
    if pence_change < 0:
        missing_amount = prompt_cost - prompt_insert_money
        print("Sorry, you do not have the sufficient amount inserted in!", "You are missing", int(missing_amount), "pence!")
        list.append(coins[6])
        break
    if pence_change == 0:
        list.append(coins[6])
        break
    if pence_change >= 50:
        list.append(coins[0])
        pence_change - 50
        break
    elif pence_change >= 20:
        list.append(coins[1])
        pence_change - 20
        break
    elif pence_change >= 10:
        list.append(coins[2])
        pence_change - 10
        break
    elif pence_change >= 5:
        list.append(coins[3])
        pence_change - 5
        break
    elif pence_change >= 2:
        list.append(coins[4])
        pence_change - 2
        break
    elif pence_change >= 1:
        list.append(coins[5])
        pence_change - 1
        break
print("You have received the following coins:", list)

最佳答案

您在这里所做的只是获得所需的第一枚硬币。在最基本的层次上,您要做的是不断迭代硬币,直到pence_change为0。

prompt_cost = int(input("What are the total cost in pence? "))
prompt_insert_money = int(input("Insert the amount of pence (max 100p) into the machine: "))
coins = ["50p", "20p", "10p", "5p", "2p", "1p", "0p"]
lst = []

pence_change = prompt_insert_money - prompt_cost
if pence_change < 0:
    missing_amount = prompt_cost - prompt_insert_money
    print("Sorry, you do not have the sufficient amount inserted in!", "You are missing", int(missing_amount), "pence!")
    lst.append(coins[6])

while pence_change >= 0:
    if pence_change == 0:
        lst.append(coins[6])
        break
    if pence_change >= 50:
        lst.append(coins[0])
        pence_change -= 50
    elif pence_change >= 20:
        lst.append(coins[1])
        pence_change -= 20
    elif pence_change >= 10:
        lst.append(coins[2])
        pence_change -= 10
    elif pence_change >= 5:
        lst.append(coins[3])
        pence_change -= 5
    elif pence_change >= 2:
        lst.append(coins[4])
        pence_change -= 2
    elif pence_change >= 1:
        lst.append(coins[5])
        pence_change -= 1
print("You have received the following coins:", lst)

07-26 01:48