Teach Your Kids To Code: A Parent-friendly Guide to Python Programming

(vip2019) #1
Numbers and Variables: Python Does the Math 37

s ntax y errors: What did you say?


While we’re typing in the Python shell, we have a chance to learn
about syntax errors. Whenever Python, or any programming lan-
guage, can’t understand the command you typed, it may respond
with a message like "Syntax Error". This means there was a prob-
lem with the way you asked the computer to do something, or your
syntax.
Syntax is the set of rules we follow in building sentences or
statements in a language. When we program computers, we call a
mistake in a statement a syntax error; when we make a mistake
in a sentence in English, we might call it bad grammar. The differ-
ence is that, unlike English speakers, computers can’t understand
bad grammar at all. Python, like most programming languages,
is very good at performing calculations as long as we follow syntax
rules, but it can’t understand anything we’re saying if we mess up
the syntax. Take a look at Figure 3-3 to see some examples of syn-
tax errors, followed by the expressions stated in a way that Python
can understand.


Figure 3-3: Learning to speak Python’s language


When we ask Python “What is 4 + 2?” in regular English,
Python responds with "SyntaxError: invalid syntax" to let us know
that it can’t understand what we’ve asked it to do. When we give
Python the correct expression, 4 + 2, Python will answer correctly
every time: 6. In the same way, an extra character, like the equal
sign at the end of the statement 3 + 3 =, confuses Python because
Python sees the equal sign as an assignment operator to assign a
value to a variable. When we type 3 + 3 and press enter, Python
understands and will always give the right answer: 6.

Free download pdf