[Tutor] If statement The Python Tutorial 3.4.1

Alan Gauld alan.gauld at btinternet.com
Sun Sep 7 01:49:39 CEST 2014


On 06/09/14 00:29, Gregory Donaldson wrote:

> This is what it looks like when I try to get it to work.
>
>>>> x = int(input("Please enter an integer: "))
>
> Please enter an integer: 42
>
>>>> if x < 0:
>
> x = 0
>
> print('Negative changed to zero')

I'm guessing that you actually indented the two lines
above but not the one below - otherwise you'd get an
indentation error by now, not a syntax error below.

> elif x == 0:
>
> SyntaxError: invalid syntax

Are you sure this is where you get the syntax error?
Or did you maybe hit enter too many times thus ending
the if block?


It needs to follow this pattern:

if x < 0:
    x = 0
    print('Negative changed to zero')
elif x == 0:
    print('you typed zero')
else:
    print('alls well')

So the if/elif and else lines are all lined up with each
other and the indented lines are likewise lined up.
And if working in the interactive prompt you must not
have blank lines (Note: You can have blanks when creating
a program file)

Indentation is always important in programming for readability,
but in Python its vital for Python to understand your code
correctly.

HTH
-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.flickr.com/photos/alangauldphotos



More information about the Tutor mailing list