Hacking Secret Ciphers with Python

(Ann) #1
Chapter 3 – The Interactive Shell 29

Because the operator is evaluated first, 2 + 4 3 + 1 evaluates to 2 + 12 + 1 and
then evaluates to 15. It does not evaluate to 6 * 3 + 1, then to 18 + 1, and then to 19.
However, you can always use parentheses to change which should operations should happen first.
Type the following into the interactive shell:





(2 + 4) * (3 + 1)
24





Evaluating Expressions


When a computer solves the expression 10 + 5 and gets the value 15 , we say it has evaluated
the expression. Evaluating an expression reduces the expression to a single value, just like solving
a math problem reduces the problem to a single number: the answer.


An expression will always evaluate (that is, shorten down to) a single value.

The expressions 10 + 5 and 10 + 3 + 2 have the same value, because they both evaluate to
15. Even single values are considered expressions: The expression 15 evaluates to the value 15.


However, if you type only 5 + into the interactive shell, you will get an error message.





5 +
SyntaxError: invalid syntax





This error happened because 5 + is not an expression. Expressions have values connected by
operators, but in the Python language the + operator expects to connect two values. We have only
given it one in “5 + ”. This is why the error message appeared. A syntax error means that the
computer does not understand the instruction you gave it because you typed it incorrectly. This
may not seem important, but a lot of computer programming is not just telling the computer what
to do, but also knowing exactly how to tell the computer to do it.


Errors are Okay!


It’s perfectly okay to make errors! You will not break your computer by typing in bad code that
causes errors. If you type in code that causes an error, Python simply says there was an error and
then displays the >>> prompt again. You can keep typing in new code into the interactive shell.


Until you get more experience with programming, the error messages might not make a lot of
sense to you. You can always Google the text of the error message to find web pages that talk
about that specific error. You can also go to http://invpy.com/errors to see a list of common
Python error messages and their meanings.

Free download pdf