Skip to main content

Python Statements

Python Statements

A statement is an instruction that the Python interpreter can execute.

Python instructions end with a newline character. This means that every line in a Python script is an instruction.

For example, a = 100 is an assignment statement. where a is a variable name and 100 is its value. There are other kinds of statements such as if statement, for statement, while statement, etc., which will be discussed in following pages.

A Python script usually contains a sequence of statements. If there is more than one statement, the result appears only one time when all statements execute.

For example:

  
print('Hello') # statement 1
x = 20 # statement 2
print(x) # statement 3
Hello
20

Multiple Statements on a single line

You can add multiple statements on a single line by separating them with semicolons, as follows:

a = 1; b = 2; c = 3  	 # three statements in a single 
print('Sum:', a + b + c) # statement 4
# Output Sum: 6

Multi-Line Statements

In Python, the end of a statement is marked by a newline character. But it is possible to extend an instruction over multiple lines in two ways called explicit continuation and implicit continuation respectively.

Explicit continuation

In explicit continuation, you can extend an instruction over multiple lines with the line continuation character (\).


sum = 1 + 2 + 3 + \
4 + 5 + 6 + \
7 + 8 + 9
print(sum)
# Output: 45

Implicit continuation

Implicit continuation can be achieved in several ways.

You can use () parentheses to write a statement on multiple lines. In this way, anything added inside a () parenthesis will be treated as a single statement, even if placed on multiple lines.

sum = (1 + 2 + 3 +
4 + 5 + 6 +
7 + 8 + 9)
print(sum)
# Output: 45
note

As can be seen, the line continuation character (\) has been removed when using () parentheses.

In a similar way, you can use the square brackets [] to create a list. Then, if necessary, you can put each element of the list on a single line for better readability.

# list of colors
colors = ['red',
'blue',
'green']
print(colors)

As with square brackets, we can use curly brackets { } to create a dictionary, with each key-value pair on a new line for better readability.

# dictionary name as a key and mark as a value  
# string:int
students = {'Tom': 70,
'Rayan': 65,
'Eliza': 75}
print(students)