Chapter 2. Variables and Statements
In the previous chapter, we used operators to write expressions that perform arithmetic computations.
In this chapter, you’ll learn about variables and statements, the import
statement, and the print
function. And I’ll introduce more of the vocabulary we use to talk about programs, including “argument” and “module.”
Variables
A variable is a name that refers to a value. To create a variable, we can write an assignment statement like this:
n
=
17
An assignment statement has three parts: the name of the variable on the left, the equals operator, =
, and an expression on the right. In this example, the expression is an integer. In the following example, the expression is a floating-point number:
pi
=
3.141592653589793
And in the following example, the expression is a string:
message
=
'And now for something completely different'
When you run an assignment statement, there is no output. Python creates the variable and gives it a value, but the assignment statement has no visible effect. However, after creating a variable, you can use it as an expression. So we can display the value of message
like this:
message
'And now for something completely different'
You can also use a variable as part of an expression with arithmetic operators:
n
+
25
42
2
*
pi
6.283185307179586
And you can use a variable when you call a function:
round
(
pi
)
3
len
(
message
)
42
State Diagrams
A common way to represent variables on paper is to write ...
Get Think Python, 3rd Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.