我的硬币编码游戏python代码中有这个问题,问题是当它询问“是头还是尾巴?”时我只是说1或Heads(与2和Tails相同)而没有引号和引号,它并不能为我提供所需的答案。
我尝试在答案中使用引号,但这似乎也不起作用。
import random
money = 100
#Write your game of chance functions here
def coin_flip(choice, bet):
choice = input("Heads or Tails?")
coinnum = random.randint(1, 2)
if coinnum == 1:
return 1
elif coinnum == 2:
return 2
win = bet*2
if choice == "Heads" or "1":
return 1
elif choice == "Tails" or "2":
return 2
if choice == coinnum:
print("Well done! You have won " + str(win) + " Dollars!")
elif choice != coinnum:
print("Sorry, you lost " + str(bet) + " Dollars!")
coin_flip("Heads", 100)
预期输出是“做得好!您赢了200美元!”或“对不起,您损失了100美元!”
答案 0 :(得分:2)
这里要注意的第一件事是您使用return
似乎是错误的。请查阅有关如何编写函数以及如何使用return
的教程。
我认为这就是您想要做的:
import random
money = 100
#Write your game of chance functions here
def coin_flip(choice, bet):
choice = input("Heads or Tails? ")
coinnum = random.randint(1, 2)
win = bet*2
if choice == "Heads" or choice == "1":
choicenum = 1
elif choice == "Tails" or choice == "2":
choicenum = 2
else:
raise ValueError("Invalid choice: " + choice)
if choicenum == coinnum:
print("Well done! You have won " + str(win) + " Dollars!")
else:
print("Sorry, you lost " + str(bet) + " Dollars!")
coin_flip("Heads", 100)
现在,让我们来看看我在您的代码中发现的错误:
return
完全不合适,我不确定您打算在这里做什么。if choice == "Heads" or "1"
无效,"1"
始终取值为true
。正确的是:if choice == "Heads" or choice == "1":
elif choice != coinnum:
是不必要的,如果它没有遇到if choice == coinnum:
,那么简单的else:
就足够了。