Statements
Contents
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.
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.
1colors = ["red", "green", "blue"]
2colors = [
3 "red",
4 "green",
5 "blue",
6]
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.
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.
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.
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.
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.
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.
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 line1
controls lines2
-12
.The
if
header on line2
controls lines3
-4
The
elif
header on line5
controls lines6
-7
The
elif
header on line8
controls lines9
-10
Lines
11
-12
are inside the function, but not theif
statementLines
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
ordef
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 anelse
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