import random
dice1 = random.randint(1, 6)
dice2 = random.randint(1, 6)
print(dice1, dice2)
user_in = "Odd"
odd = [1, 3, 5, 7, 9, 11]
even = [2, 4, 6, 8, 10, 12]
def cho_han(dice1, dice2, money1, user_in):
if (dice1 + dice2 == odd) and user_input == "Odd":
return "Odd! You Won $" + str(money1 * 2)
elif (dice1 + dice2 == odd) and user_in != "Odd":
return "Odd! You lost $" + str(money1)
elif (dice1 + dice2 == even) and user_in == "Even":
return "Even! You Won $" + str(money1 * 2)
else:
return "Even! You lost $" + str(money1)
print(cho_han(dice1, dice2, 300, user_in))
无论我为变量user_in
输入什么,它将始终显示"Even! You lost $300"
很抱歉遇到这样的小问题,我是python和程序设计的新手,只是想学习。
感谢任何可以提供帮助的人!
答案 0 :(得分:1)
注意dice1 + dice2 in odd
,整数值不能等于list。
def cho_han(dice1, dice2, money1, user_in):
if (dice1 + dice2 in odd) and user_in == "Odd":
return "Odd! You Won $" + str(money1 * 2)
elif (dice1 + dice2 in odd) and user_in != "Odd":
return "Odd! You lost $" + str(money1)
elif (dice1 + dice2 in even) and user_in == "Even":
return "Even! You Won $" + str(money1 * 2)
else:
return "Even! You lost $" + str(money1)
答案 1 :(得分:0)
我想对代码进行以下更改:
cho_han
内调用重构此代码
import random
def get_dices():
dice1 = random.randint(1, 6)
dice2 = random.randint(1, 6)
print(dice1, dice2)
return dice1, dice2
user_in = "Odd"
user_parity = True if user_in.lower() == 'even' else False
def cho_han(money1, user_parity):
dice1, dice2 = get_dices()
result_parity = (dice1 + dice2) % 2 == 0
result_parity_str = "Even" if result_parity else "Odd"
if result_parity == user_parity:
return "{}! You Won {}".format(result_parity_str, str(money1))
else:
return "{}! You lost {}".format(result_parity_str, str(money1))
print(cho_han(300, user_parity))
如果决定测试代码,则可以mock get_dices()
。