[Tutor] SyntaxError with indentation (was: 2 Very basic queries)

Ben Finney ben+python at benfinney.id.au
Wed Mar 26 02:00:35 CET 2014


Saad Bashir <bashir.saad at gmail.com> writes:

> 1.  But encouraged by the site to ask event the most basic questions on
> this forum, here goes:

Welcome! Yes, even very basic questions are appropriate here.

But please try to keep separate questions in separate threads, with a
“Subject” field that indicates what the topic is. I'll restrict this
answer to the first question.

> 1. Practicing the code as given in the book:
>
>     >>> ph = float(input('Enter the pH level: '))
> Enter the pH level: 8.5
> >>> if ph < 7.0:
> ...       print(ph, "is acidic.")
> ...        elif ph > 7.0:
> ...         print(ph, "is basic.")
>
> When I write this in the Python shell, as soon as I hit return after "elif
> ph > 7.0:"
> I get an error message highlighting "elif" and saying syntax error.

Right. Programmers who read code are greatly assisted when the
indentation matches the sematic structure of the code. “Other
programmers” includes you, when you read the code later.

So, in Python, the indentation is significant and determines how the
Python compiler will parse your code.

In other words: you must tell Python the structure of your code, by
expressing that structure consistently through indentation.

Your code as you show it, above, does not have sensible indentation. The
‘if’ and ‘elif’ clauses will only be matched together if they are at the
same indentation level; for your example above, that means they need to
have no indentation.

Also, the code blocks (each ‘print’ function call) should be at the same
indentation level, relative to the ‘if’ and ‘elif’. Conventionally, they
should be indented by four spaces.

You are working from an instructional text; that will have a section
describing how Python code must be indented. Have another read of that
section, to understand better what needs to be done.

You can also read the Python community convention on coding style, PEP 8
<URL:https://www.python.org/dev/peps/pep-0008/>, to see how other
programmers will expect your code to be formatted.

> 2. Another problem is that the Python shell is allowing me to copy/paste
> any code at all.  Is there something I am not doing right?

Please start another thread for this question, by composing a new message.

> Apologies in advance for wasting everyone's time but will be very
> grateful if I am helped.

Hope that helps you!

-- 
 \           “Two hands working can do more than a thousand clasped in |
  `\                                               prayer.” —Anonymous |
_o__)                                                                  |
Ben Finney



More information about the Tutor mailing list