-1

I'm relatively new to python and don't quite understand what's going on here. I have the following code:

if cell.location != (always_empty_location
                     and random.random() < self.settings['OBSTACLE_RATIO']):

And it's broken, but if I remove the parenthesis and do a simple

and \

on the first line, it works. I can't seem to find a solid explanation of how python treats scenario's like this. Everything online suggests this should work.

John Bollinger
  • 160,171
  • 8
  • 81
  • 157
Oyster773
  • 375
  • 1
  • 10
  • Define "*it's broken*". – melpomene Nov 17 '17 at 17:21
  • 1
    Welcome to StackOverflow. Please read and follow the posting guidelines in the help documentation. [Minimal, complete, verifiable example](http://stackoverflow.com/help/mcve) applies here. We cannot effectively help you until you post your MCVE code and accurately describe the problem. We should be able to paste your posted code into a text file and reproduce the problem you described. – Prune Nov 17 '17 at 17:22
  • @melpomene - My tests go crazy, I'm getting a completely different behaviour. – Oyster773 Nov 17 '17 at 17:22

2 Answers2

3

This has nothing to do with line breaks, it's just that

if a != b and c < d:

is very different from

if a != (b and c < d):

The first condition parses as (a != b) and (c < d) whereas the second condition parses as a != (b and (c < d)).

melpomene
  • 84,125
  • 8
  • 85
  • 148
0

In Python, you can only do multi-line conditionals if you wrap it in paren or if you use \.

So this works:

if foo == 1 and \
     bar == 2:
   do_something()

And this will work:

if (foo == 1 and
      bar == 2):
    do_something()

What you did, however, was putting a parenthesis around half of a condition!

if foo == (1
       and bar == 2):
    do_something()

So what is happening here is that it's evaluating (1 and bar == 2), and then testing foo for that value. If foo == True then that would work. But if foo == False and bar != 2, then it'll pass.

cwallenpoole
  • 79,954
  • 26
  • 128
  • 166