Skip to Content
Think Python, 3rd Edition
book

Think Python, 3rd Edition

by Allen Downey
May 2024
Beginner to intermediate
328 pages
6h 5m
English
O'Reilly Media, Inc.
Content preview from Think Python, 3rd Edition

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 ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Head First Python, 3rd Edition

Head First Python, 3rd Edition

Paul Barry

Publisher Resources

ISBN: 9781098155421Errata PageSupplemental Content