Python - Невозможно сопоставить значение из списка - PullRequest
0 голосов
/ 23 сентября 2019
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 ]

1 голос
/ 23 сентября 2019

Примечание dice1 + dice2 in odd, целочисленное значение не может быть равно списку.

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)
0 голосов
/ 23 сентября 2019

Я хотел бы внести следующие изменения в код:

  • Четность (четная или нечетная) является двоичной.Это не обязательно должен быть строковый ввод
  • Избавьтесь от таблицы поиска, поскольку она не очень хорошо масштабируется
  • Поместите код в функцию, которую можно снова вызывать и легко тестировать
  • Переместите случайный вызов в другую функцию и вызовите его внутри 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))

Если вы решите проверить свой код, выможет макет get_dices().

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...