-3

Whenever I run this function, the output is

You found emerald!

Why? With a tiny 3/999 chance of finding emerald, I should usually find something else. It cannot be pure chance. I have reviewed the code and I can't find the issue.

block=randint(1,1000)
    if block==456 or 742 or 327:
        print('You found emerald!')
    elif block==275 or 467 or 234 or 978 or 10 or 3 or 256 or 475 or 103 or 701 or 124 or 9:
        print('You found diamond!')
    elif block==range(900,930):
        print('You found iron!')
    elif block==range(800,870):
        print('You found coal!')
    else:
        print('You found stone...')
jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
Anonymous
  • 33
  • 9

2 Answers2

2

While your condition might make sense in English, it doesn't actually do what you expect it to do in python. Let's break it down.

if block==456 or 742 or 327:

What you have here is a boolean statement with a true/false value, that's composed of three sub-statements:

if (block==456) or (742) or (327):

That's because the way python syntax works, == is a binary operator (meaning it has two operands, one on the left, one on the right) and or is, likewise, a binary operator. So the python interpreter doesn't parse it as:

if block == (456 or 742 or 327):

merely because, well, that's not how python was designed to work.

So why does emerald get picked every time? because in this statement:

if (block==456) or (742) or (327):

you're checking the true/false value of the number "742". As per python's rules (and many other languages as well), the value "0" will be evaluated as false, but any other number will count as true. So your test resolves to:

if (block==456) or (True) or (True):

And that means it will always return True, which is why it will always enter the first conditional branch, and return the rarest result.

As others have mentioned in the comments, what you want isn't an equality check, but a check that the value is contained in a list:

if block in (456, 742, 327):

This will check if the value of block is inside the list of values specified.

Avner Shahar-Kashtan
  • 14,492
  • 3
  • 37
  • 63
1

Why because your conditionals boil down to

if (block==456) or (742) or (327):

Anything other than a 0 is evaluated to True. In this case, 742 evaluated to True and hence print('You found emerald!') gets executed.

Change your tests to either

if (block==456) or (block==742) or (block==327) or if block in (456,742,327)

Xnkr
  • 564
  • 5
  • 16