Page 52 - Python Basics: A Practical Introduction to Python 3
P. 52
3.3. Create a Variable
Values are assigned to variable names using a special symbol called
the assignment operator (=) . The = operator takes the value to the
right of the operator and assigns it to the name on the left.
Let’s modify the hello_world.py file from the previous section to assign
some text in a variable before printing it to the screen:
>>> greeting = "Hello, World"
>>> print(greeting)
Hello, world
On the first line, you create a variable named greeting and assign it the
value "Hello, World" using the = operator.
print(greeting) displays the output Hello, World because Python looks
for the name greeting, finds that it’s been assigned the value "Hello,
World", and replaces the variable name with its value before calling
the function.
If you hadn’t executed greeting = "Hello, World" before executing
print(greeting), then you would have seen a NameError like you did
when you tried to execute print(Hello, World) in the previous section.
Note
Although = looks like the equals sign from mathematics, it has a
different meaning in Python. This distinction is important and
can be a source of frustration for beginner programmers.
Just remember, whenever you see the = operator, whatever is to
the right of it is being assigned to a variable on the left.
Variable names are case sensitive, so a variable named greeting is
not the same as a variable named Greeting. For instance, the following
code produces a NameError:
51