Statements and Expressions
Statements
and Expressions
are fundamental units that compose a program.
Statements
A statement
is a code block that directs the program to perform a specific task.
Statements can take various forms, such as the following:
Assignment Statement
It stores a value in a variable (a container for data) for reuse later.
To assign a value to a variable, use the =
symbol.
number = 10 # A statement assigning 10 to the variable number
Conditional Statement
Executes a specific part of the code based on a condition.
Use the keywords if
, elif
, else
and must append a colon (:) at the end of the line.
if number > 5: # If number is greater than 5 print("The number is greater than 5") # Statement to print 'The number is greater than 5'
Loop Statement
Executes a part of the code multiple times as long as a certain condition is met.
Use the keywords for
, while
and must append a colon (:) at the end of the line.
for i in range(3): # Repeats from 0 to 2 print(i + 5) # Statement to print i + 5
-
for
defines a loop, andi in range(3)
denotes the loop range. -
The indented code block under the colon (:) defines what to execute on each loop iteration. The above example adds 5 to
i
and prints the result for each loop iteration. -
i
is the variable used in the loop, taking values 0, 1, and 2 in sequence. Each iteration of the code block incrementsi
by 1. -
The
range
function generates a series of numbers, and range(3) generates numbers from 0 to 2. -
The loop above runs print(i + 5), outputting 5, 6, and 7 when
i
is 0, 1, and 2, respectively.
Programs process data, execute code based on conditions, and perform repetitive tasks using various statements.
a = 1 # Variable assignment statement for i in range(3): # Loop statement if i == 1: # Conditional statement print(i) # Print statement
Expressions
An expression
is a unit of code that yields a value.
Expressions are evaluated to produce a single value.
Expressions can be part of a statement and are used as a portion of the task the statement performs.
# An expression that returns 7 3 + 4 # An expression that generates the string "Hello World" "Hello" + " " + "World"
Difference Between Statements and Expressions
Statements are executed
code, while expressions are code that produce a value
.
In simple terms, statements tell Python what to do, whereas expressions tell it what to calculate or evaluate.
For example, in the code below, 5 + 3
is an expression, while a = 5 + 3
is a statement that assigns the value 8 to the variable a
.
a = 5 + 3
Coding Practice
Complete the conditional statement by typing if number > 5:
.
Be careful not to forget the trailing colon(:)
! Omitting it results in a syntax error.
Which of the following is an expression in Python?
for i in range(3):
if number > 5:
3 + 4
number = 10
Guidelines
AI Tutor
Publish
Design
Upload
Notes
Favorites
Help
Code Editor
Execution Result