Greg Peckory
Greg Peckory

Reputation: 8058

Ifs and elifs wont work properly in roulette game - python

Ok so I am making a roulette game. The random number that the spinner lands on is called 'figure'. It is a very basic and simple code but it won't seem to work for me properly. At the moment you either pick a specific number or choose 1 - 18. I've tried many different ways and still no luck. Here is my code. If anyone knows what the problem is please let me know. Thanks:

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"))

Upvotes: 0

Views: 253

Answers (2)

Joey
Joey

Reputation: 354506

The problem is that Python thinks the following:

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

Boolean operators have a lower precedence than comparison operators so the code is not doing what you intended. Instead the strings at the end are each interpreted as operands of or and thus interpreted as a boolean value, which is always True in this case.

You can rewrite it in the following way:

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

or probably even removing spaces from the string so you only need to compare against a single value:

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

Upvotes: 1

Martijn Pieters
Martijn Pieters

Reputation: 1121834

Look at:

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

Here you have several statements that always evaluate to True; each of '1 - 18' or '1- 18' or '1 -18' is a a non-empty string. It doesn't matter what values int(figure) or d have. This means python sees that line as the equivalent of if something or True.

What you want to do instead is use the in operator to test if your d is part of a list of options:

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

The same problem applies to your elif statement.

Upvotes: 3

Related Questions