The else Statement for When if Condition is False
The else
statement is used with the if
statement in conditional logic to define a code block that executes when the if
condition is false.
Structure of if, else Statement
if condition1: # Code to execute if condition1 is true else: # Code to execute if all conditions are false
How is the else Statement Used?
The else
statement follows an if
statement and does not include a condition.
Always add a colon :
at the end of the else
code line to signify the block of code that the else statement applies to.
Example of else Statement
number = 3 # Check if number is divisible by 2 if number % 2 == 0: # Executes if number is divisible by 2 print("It is even.") else: # Executes if number is not divisible by 2 print("It is odd.")
Quiz
0 / 1
Example of an else statement
Write code to determine if a number is even or odd. If the number is divisible by 2, print 'It is even.' Otherwise, print 'It is odd.' The given number is 4
. The expected output is It is even.
number = 4
if number % 2 == 0:
print("It is even.")
else:
print(
)
Lecture
AI Tutor
Design
Upload
Notes
Favorites
Help
Code Editor
Run
Generate
Execution Result