Question

I've got this if statement in a while loop and it's set out exactly like this, but i'm struggling to understand exactly whats going on. I'm a recent convert from java and i'm having a little trouble grasping the whole 'white space matters' business and I can't find an explanation for this bit of code:

if x % 2 == 1: z = z + y
y = y << 1
x = x >> 1

Can anyone explain why the z = z + y is on the same line as the if? and why the two lines under it are not indented to the right so to be inside the if block? Thanks

Was it helpful?

Solution

This is equivalent to

if x % 2 == 1:
    z = z + y
y = y << 1
x = x >> 1

it's just shorthand for a single-line subclause.

OTHER TIPS

Is just grammatical sugar to allow the if to be in one line. Is the same as having:

x = 4
y = 5
z = 0
while x:
  if x % 2 == 1:
    z = z + y
  y = y << 1
  x = x >> 1
  print 'x: %s, y: %s, z: %s' % (x, y, z)

(I added a few extra lines to have a functioning example)

You could even shorten that to:

x = 4; y = 5; z = 0
while x:
  if x % 2 == 1: z = z + y
  y = y << 1; x = x >> 1; print 'x: %s, y: %s, z: %s' % (x, y, z)

But don't. Is not Pythonic!! :-D I also came from Java, and in the beginning, I was longing for a ; but when you get used to it, you'll find them... odd to use (at least, I find them kind of ugly, even).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top