Statements#

Table of Contents

A statement is an instruction that Python can run or execute as a unit.

Like grammar in prose, statements follow syntax rules telling Python where they begin and end as well as how they should be handled.

Python’s syntax rules define statements as either a single logical line of code:

debug_mode = True

Or a block of code grouping multiple statements together:

if result < 0:
  print("Positive number required, try again.")

Simple Statements#

A simple statement is a single instruction, one that does not group together other statements. In comparison to prose a simple statement is like a sentence. While there are exceptions, a simple statements is essentially a line of code.

To be more accurate, a simple statement is a single instruction that could be written on one line by itself, even if it is actually written differently. This is referred to as a logical line.

Single line statements#

Most of the time simple statements are written one per line. The newline character tells Python that the statement is complete.

Listing 38 examples of simple statements, each on one physical line#
name = "Alissa"
print("Hello", name)
import random
colors = ["red", "green", "blue"]

Multi-line statements#

A statement can be broken into multiple lines following an operator or delimiter symbol as long it is enclosed by ( ), [ ] or { }.

This is called implicit line continuation.

Listing 39 the same simple statement, shown in both single and multi-line formats#
1colors = ["red", "green", "blue"]
2colors = [
3  "red",
4  "green",
5  "blue",
6]
Listing 40 two simple statement examples split via implicit line continuation#
 1address = {
 2    'street': "1600 Pennsylvania Ave NW",
 3    'city': "Washington",
 4    'state': "DC",
 5    'zip': "20500-0003",
 6    'country': "United States",
 7}
 8
 9print("The White House: " +
10      address['street']   + ", " +
11      address['city']     + ", " +
12      address['state']    + ", " +
13      address['zip'])

If the operators or delimiters are not enclosed by anything you can still can break a statement into multiple lines by adding a \ to the end of each line.

This is called explicit line continuation.

Listing 41 a single assignment statement, split via explicit line continuation#
1a = 1 + 2 + 3 + \
2    4 + 5 + 6 + \
3    7 + 8 + 9

Multi-statement lines#

You can put multiple statements on one line by putting a ; between each statement. You can think of a semicolon as a substitute newline.

Listing 42 two simple statements on one physical line#
1import random; num = random.randint(1, 10)

This is usually discouraged as poor coding practice, but it’s fine in the Python shell where it can be a handy shortcut.

Compound Statements#

A compound statement is a number of statements grouped together as a single unit. If a simple statement like a sentence, a compound statement is more like a paragraph.

One example is a function definition.

Listing 43 this function has three simple statements in its suite (lines 2-4) controlled by the header (line 1)#
1def welcome_player():
2  name = input("Player name: ")
3  print("Welcome", name)
4  return name

A compound statement is made up of at least one header statement and the group of statements, called a suite, that belong to it.

A header statement always starts with a keyword (like def or if) and ends in a :. This header tells Python that a compound statement has started, that it is in charge of all of the indented lines to follow, and how and when they should be executed.

The header line and the suite of statements that belong to it are called a clause.

Multi-clause statements#

Some compound statements can have more than one clause. This allows a different set of statements to be triggered depending on the circumstances.

Here is an example of an if-statement with three clauses.

Listing 44 this is a single if-statement though it contains three clauses (the if clause lines 1-2, the elif clause lines 3-4, and the else clause lines 5-6)#
1if answer < 0:
2    print("Answer must be a positive number")
3elif answer > 5:
4    print("Answer must be less than five.")
5else:
6    print("Your answer was:", answer)

You can think of compound statements as a hierarchy where statements at the same indentation level are under the authority of the most recent header statement that’s back one indentation level.

Listing 45 an if-statement with two clauses#
1if name == "Picard":
2  print("Riker")
3  print("Data")
4  print("Worf")
5elif name == "Riker":
6  print("Data")
7  print("Worf")

In this example, the Picard header (line 1) is in charge of Riker, Data and Worf (lines 2-4), and the Riker header (line 5) is in charge of Data and Worf (lines 6 and 7).

Nested statements#

Compound statements contain other compound statements. The suites of the nested compound statements would then be indented one additional level.

An example is a function that contains an if-statement.

Listing 46 an if-statement within a function definition, followed by two simple statements#
 1def action(choice, item):
 2  if choice == "a":
 3    print("Adding item")
 4    return add(item)
 5  elif choice == "d":
 6    print("Deleting item")
 7    return delete(item)
 8  elif choice == "q":
 9    print("Quitting.")
10    exit()
11  print("Invalid response, please try again.")
12  return False
13
14response = show_menu()
15action(response)
  • The def header on line 1 controls lines 2-12.

  • The if header on line 2 controls lines 3-4

  • The elif header on line 5 controls lines 6-7

  • The elif header on line 8 controls lines 9-10

  • Lines 11-12 are inside the function, but not the if statement

  • Lines 14-15 are outside of the function entirely

Expressions vs. Statements#

An expression is any piece of code that evaluates to a value.

A statement is a logical line of code or group of statements that gives instructions to Python.

The difference can be confusing, especially since in Python there is a fair bit of overlap.

One way to think of it is:

  • if you can save the result of the code to a variable, then it is an expression

  • if the result of the code causes something to happen it is a statement

The string "hello" on a line by itself is does not cause anything to happen, therefore it is not a statement. Whereas message = "hello" causes the variable message to be assigned the value "hello".

A function call may or may not be an expression. But a function call on a line by itself is always a valid statement, since it causes the statements inside the function to be executed.

Expressions

evaluated

resolves to a value

smallest unit is a single literal value

are sometimes statements

can contain expressions

cannot contain statements

Statements

executed

an instruction to Python

smallest unit is a logical line of code

are sometimes expressions

can contain expressions

contain statements when compound

Expressions

include:

  • literal values

  • variables

  • the result of an operator between values

  • subscripting a list or dict using [ ]

may include:

  • function calls

Statements

include:

  • assignments

  • function calls

  • lines that start with non-operator keywords

Expressions

5
random
random.randint(1, 10)
[1, 2, 3]
"Last index:"
len(nums) - 1
num % 2 == 0

is_even(1)

Statements


import random
random.randint(1, 10)
nums = [1, 2, 3]
print("Last index:", len(nums) - 1)

def is_even(num):
  return num % 2 == 0
is_even(1)

Summary#

Compound statements:

  • start with a header statement that begin with a keyword like if or def and end with a :

  • followed by a suite of one or more indented statements

  • some compound statements have more than one clause, like in an if statement with an else clause

Self-Quiz#

1. How many statements are in the following:

favs = {
    'color': "purple",
    'season': "Fall",
    'food': "cheese"
}
print("My favorite color is:", favs['color'])
My favorite color is: purple

2. What is wrong with the following:

import random
num = random.randint(0, 10)
if num > 5:
print(num)
  Cell In[2], line 4
    print(num)
    ^
IndentationError: expected an indented block

3. What is wrong with the following:

def print_header(title)
    print(title)
    print("============================================")
  Cell In[3], line 1
    def print_header(title)
                           ^
SyntaxError: invalid syntax

4. How many statements are in the following:

name = "Jack" ; age = 24 ; print(name, "is", age, "years old")
Jack is 24 years old

Reference#

Glossary#

Statements#

statement#

An instruction that Python can execute as a unit.

physical line#

a line of code, the way it was written

logical line#
  • a physical line of code containing a single complete statement

  • multiple physical lines of code joned by explicit or implicit line continuation

  • a single statement part of multi-statement physical line of code

execute#

when Python runs a statement (or script)

simple statement#

a single statement that can be written on one line by itself, even if it is not actually written that way

delimiter#

a seperating symbol, most often a ,

implicit line continuation#

when a simple statement is broken into multiple lines inside of ( ), [ ] or { } after operators.

explicit line continuation#

when a simple statement is broken into multiple lines by appending a \ to the end of each line

compound statement#

a number of statements grouped together as a single unit consisting of one or more clauses, each made up of a header statement and a suite of statements the header controls

header#

the first line in a compound statement clause, beginning with a keyword and ending with a :, that controls when and how the suite of statements in the clause will be executed.

body#
suite#

a group of statements in a compound statement that are controlled by a header

clause#

a header and the suite of statements that it controls in a compound statment


See also#

See also

The Python Language Reference