Guidelines

Controlling Program Flow with if Statements

In programming, a conditional statement is used to execute a block of code if a specified condition is true (True), and execute alternative code if it is false.

In Python, these conditional logics are implemented using the if, elif (short for else if), and else keywords.

Below is an example of a conditional statement code that determines whether a number is even.

Example of if, else statement
number = 4 if number % 2 == 0: print("It is an even number.") else: print("It is an odd number.")

Here, number % 2 == 0 is the condition, and when this condition is true (when the number is an even number divisible by 2), the first print statement ("It is an even number.") is executed.

Otherwise (when the number is odd), the code under else ("It is an odd number.") is executed.


Structure of the if Statement

An if statement executes a block of code only when a specified condition is true (True), and you should always end the part indicating the condition with a colon (:).

Structure of the if Statement
if condition: # Code to execute if the condition is true

Note that the code block that is executed when the condition is true must be indented.

Here is an example code that checks whether the variable number is greater than 0.

Example of if Statement
number = 5 if number > 0: # The condition is true, so the following code is executed print("It is a positive number.") # Indentation to the left of print indicates the code block
Mission
0 / 1

What is the most appropriate word to fill in the blank?

In Python, always end an if statement with a .
()
;
:
{}

Guidelines

AI Tutor

Publish

Design

Upload

Notes

Favorites

Help

Code Editor

Run
Generate

Execution Result