Python-无法匹配列表中的值

时间:2019-09-23 07:27:04

标签: python python-3.x if-statement

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和程序设计的新手,只是想学习。

感谢任何可以提供帮助的人!

2 个答案:

答案 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()