Variable and Expressions in Python

Variable and Expressions in Python

Python’s syntax for variables and expressions is close to what you would see in C or Java, so you can skim this section if it starts looking familiar. However, you should take note of Python’s loose typing (see below).


Python understands the standard arithmetic operators, including +, -, / (division), and * (multiplication). The Python interpreter makes a handy calculator:

>>> 8/2
>>> 5+4*6

Note that the second example evaluates 29 (and not 54); the interpreter multiplies 4 by 6 before adding 5. Python uses operator precedence rules to decide what to do first. You can control order explicitly by using parentheses:

>>> (5+4)*6

In practice, it’s often easiest to use parentheses (even when they aren’t required) to make code more readable.


You can use variables to hold values over time. For example, this code computes how long it takes to watch every episode of Monty Python’s Flying Circus (including the two German episodes of Monty Python’s Fliegende Zirkus):

>>> NumberOfEpisodes=47
>>> EpisodeLength=0.5
>>> PythonMarathonLength=(NumberOfEpisodes*EpisodeLength)
>>> PythonMarathonLength

A variable is always a reference to a value. Variables do not have types, but objects do. (Python is loosely typed; the same variable may refer to an integer value in the morning and a string value in the afternoon.)

Python does not require variable declarations. However, you cannot access a variable until you have assigned it a value. If you try to access an undefined variable, the interpreter will complain (the wording of the error may be different in your version of Python):

>>> print Scrmptious
Traceback (most recent call last):
File “<stdin>”, line 1, in ?
NameError: There is no variable named ‘Scrumptious’

This example raised an exception. In Python, most errors are represented by exception objects that the surrounding code can handle. Chapter 5 describes Python’s exception-handling abilities.

Python is case-sensitive. This means that names that are capitalized differently refer to different variables:

>>> FavoriteColor=”blue”
>>> favoritecolor=”yellow”
>>> print FavoriteColor,favoritecolor
blue yellow

No comments:

Post a Comment