Login
📚 Introduction to Python Programming
Chapters ▾

Chapter 2: Expressions

Grace Murray Hopper at the UNIVAC keyboard
Figure 2.1 credit: modification of work "Grace Hopper at Univac I console", courtesy of the Computer History Museum

A computer program is a sequence of statements that run one after the other. In Python, many statements consist of one or more expressions. An expression represents a single value to be computed. Ex: The expression 3*x - 5 evaluates to 7 when x is 4. Learning to recognize expressions opens the door for programming all kinds of interesting calculations.

Expressions are often a combination of literals, variables, and operators. In the previous example, 3 and 5 are literals, x is a variable, and * and - are operators. Expressions can be arbitrarily long, consisting of many calculations. Expressions can also be as short as one value. Ex: In the assignment statement x = 5, the literal 5 is an expression.

The Statements chapter introduced simple expressions like 1 * 2 and "Hi " + "there". This chapter explores other kinds of expressions for working with numbers and strings. The first section shows a great way to experiment with expressions using a Python shell. Later sections present more details about integers and floating-point numbers, explain how to import and use the math module, and show how to make long lines of code easier to read.

Adapted from Introduction to Python Programming by OpenStax (openstax.org), licensed under CC BY-NC-SA 4.0. Changes were made. License: CC-BY-NC-SA-4.0.