Python-无法与列表中的值匹配
无论我在中为变量Python-无法与列表中的值匹配,python,python-3.x,if-statement,Python,Python 3.x,If Statement,无论我在中为变量user\u输入了什么,它都会打印“甚至!你损失了300美元” 很抱歉有这么一个小问题,我对python和编程都是新手,我只是想学习一下 谢谢所有能帮忙的人 注意dice1+dice2在奇数中,整数值不能等于list import random dice1 = random.randint(1, 6) dice2 = random.randint(1, 6) print(dice1, dice2) user_in = "Odd" odd = [1, 3, 5, 7, 9, 1
user\u输入了什么,它都会打印“甚至!你损失了300美元”
很抱歉有这么一个小问题,我对python和编程都是新手,我只是想学习一下
谢谢所有能帮忙的人 注意dice1+dice2在奇数中
,整数值不能等于list
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))
我想对代码进行以下更改:
- 奇偶校验(偶数或奇数)是二进制的。它不必是字符串输入
- 去掉查找表,因为它不能很好地扩展
- 将代码放在一个可以再次调用且易于测试的函数中
- 将调用移到另一个函数中的random,并在
cho_han
重新构造此代码并编写此代码
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)
如果您决定测试代码,您可以get_dies()
,这可能是因为整数dice1+dice2
永远不等于一个列表,例如odd
或偶
。你想用吗?看看dice1+dice2==odd
。使用dice1+dice2
创建一个整数值,并检查它是否与列表odd
相同。那是不可能的。您想检查该值是否在列表中:(dice1+dice2)为奇数。非常感谢大家!这有助于澄清问题并帮助我了解:)顺便说一句,这并不重要,但如果你有更大的查找列表,你可能会想使用集
odd=[1,3,5,7,9,11]
vs.odd={1,3,5,7,9,11}
。列表中的查找是O(N),而集合中的查找是O(1)。如果你不知道这个符号:在集合中查找更快。在If语句中键入user\u inputYeah!谢谢@Vikas
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))