我正在尝试学习Python,但我仍然无休止地陷入同样的问题。 在我做的练习中,用户需要插入 5、10 或 25 的硬币(没有其他),直到他/她达到 50。
但是当我运行脚本时,总是要求我插入硬币。没有被告知还剩下什么。
这是我的代码:
amount_to_reach = 50
money = int(input("Insert coin"))
if money != 10 and money != 5 and money != 25:
print("Amount Due: 50")
else:
while money < 50:
money = money + int(input("Insert coin"))
print(f"Amount due: {money - amount_to_reach}")
这是我的输出:
Insert coin 5
Insert coin 5
...
Insert coin 5
无尽
好的,这是新版本,现在可以使用了:
amount_to_reach = 50
money = int(input("Insert coin"))
if money != 10 and money != 5 and money != 25:
print("Amount Due: 50")
else:
while money < 50:
money = money + int(input("Insert coin"))
print(f"Amount due: {money - amount_to_reach}")
print(f"Change Owed: {money - amount_to_reach}")
这是我认为的答案。非常感谢有关“循环内部”的观点:
amount_to_reach = 50
money = int(input("Insert coin"))
if money != 10 and money != 5 and money != 25:
print("Amount Due: 50")
else:
while money < 50:
money = money + int(input("Insert coin"))
print(f"Amount due: {money - amount_to_reach}")
print(f"Change Owed: {money - amount_to_reach}")
通过阅读评论,似乎您正在尝试做类似的事情:
amount_to_reach = 50
money = 0
while money < amount_to_reach:
coin = int(input("Insert coin : "))
if coin not in [5, 10, 25]:
print("Invalid coin! Please insert a coin of 5, 10, or 25 cents.")
continue # Restart the loop without updating money
money += coin
remaining = amount_to_reach - money
if remaining > 0:
print(f"Remaining amount: {remaining} cents")
print(f"Amount due: {money - amount_to_reach}")
输出:
Insert coin : 25
Remaining amount: 25 cents
Insert coin : 5
Remaining amount: 20 cents
Insert coin : 10
Remaining amount: 10 cents
Insert coin : 10
Amount due: 0