Game Development Reference
In-Depth Information
2 - The Interactive Shell
This is like how a cat is a type of pet, but not all pets are cats. Someone could have a pet
dog or a pet lizard. An expression is made up of values (such as integers like 8 and 6)
connected by an operator (such as the * multiplication sign). A single value by itself is also
considered an expression.
In the next chapter, we will learn about working with text in expressions. Python isn't
limited to just numbers. It's more than just a fancy calculator!
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.
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 just type 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 the + operator always expects to connect two things in Python.
We have only given it one. 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. Python will always display an error message if you enter an instruction that it
cannot understand.
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.
Expressions Inside Other Expressions
Expressions can also contain other expressions. For example, in the expression 2 + 5
+ 8 , the 2 + 5 part is its own expression. Python evaluates 2 + 5 to 7 , so the original
expression becomes 7 + 8 . Python then evaluates this expression to 15 .
Think of an expression as being a stack of pancakes. If you put two stacks of pancakes
together, you still have a stack of pancakes. And a large stack of pancakes can be made up
of smaller stacks of pancakes that were put together. Expressions can be combined together
to form larger expressions in the same way. But no matter how big an expression is it also
evaluates to a single answer, just like 2 + 5 + 8 evaluates to 15 .
Search WWH ::




Custom Search