Ifs和elifs在轮盘赌游戏中无法正常工作 - 蟒蛇

时间:2012-07-04 12:53:21

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

好的,所以我正在制作轮盘游戏。旋转器所在的随机数称为“数字”。这是一个非常基本和简单的代码,但它似乎不适合我。 目前你要么选择一个特定的数字,要么选择1 - 18.我尝试了很多不同的方法但仍然没有运气。这是我的代码。如果有人知道问题是什么,请告诉我。感谢:

numbers = ['1', '2', '3'.......'35', '36']

figure = choice(numbers)

d = textinput("Pick bet", "")

if int(figure) > 18 and d == '1-18' or '1 - 18' or '1- 18' or '1 -18':
    pu()
    goto(100,100)
    write("Loser", font = ("Comic Sans MS", 30, "bold"))

elif int(figure) < 19 and d == '1-18' or '1 - 18' or '1- 18' or '1 -18':
    pu()
    goto(10,100)
    write("Well done", font = ("Comic Sans MS", 30, "bold"))


elif int(d) in range(36) and int(figure) == int(d):
    pu()
    goto(100,100)
    write("Well done", font = ("Comic Sans MS", 30, "bold"))

elif int(d) in range(36) and int(figure) != int(d):
    pu()
    goto(100,100)
    write("Loser", font = ("Comic Sans MS", 30, "bold"))

2 个答案:

答案 0 :(得分:3)

看看:

if int(figure) > 18 and d == '1-18' or '1 - 18' or '1- 18' or '1 -18':

这里有几个总是评估为True的语句;每个'1 - 18' or '1- 18' or '1 -18'都是一个非空字符串。 int(figure)d的值是什么并不重要。这意味着python认为该行等同于if something or True

您想要做的是使用in运算符来测试您的d是否属于选项列表的一部分:

if int(figure) > 18 and d in ('1-18', '1 - 18', '1- 18', '1 -18'):

同样的问题适用于您的elif声明。

答案 1 :(得分:1)

问题是Python认为如下:

if (int(figure) > 18 and d == '1-18') or '1 - 18' or '1- 18' ...

布尔运算符的优先级低于比较运算符,因此代码没有按照您的意图执行。相反,最后的字符串每个都被解释为or的操作数,因此被解释为布尔值,在这种情况下始终为True

您可以通过以下方式重写它:

if int(figure) > 18 and d in ['1-18', '1 - 18', '1- 18', '1 -18']

或甚至可能从字符串中删除空格,因此您只需要与单个值进行比较:

if int(figure) > 18 and d.replace(' ', '') == '1-18'