In Python, the if statement is used for conditional execution of code. It allows you to specify a block of code that will be executed only if a certain condition is met.
The basic syntax of an if statement in Python is as follows:
if condition:
# indented code to be executed if the condition is True
You can also include an else block to specify code that should be executed when the condition is not met
mood = input("Are you happy?")
if mood == "happy":
print("Clap your hands")
Note how what we are checking equivalence we use double equals, not single.
You can also include an else block to specify code that should be executed when the condition is not met.
if condition:
# code to be executed if the condition is True
else:
# code to be executed if the condition is False
if name == "Richard":
print("You have a good name")
else:
print("Meh!")
In an if-else statement, what happens if the condition is false?
What is the purpose of an if-else statement?
What does a nested if-else statement do?
What is the purpose of a chained if-else statement?
The if-elif-else statement is used when you have multiple conditions to check in a sequence. It allows you to test each condition one by one, and as soon as one of the conditions is satisfied, the corresponding block of code will be executed, and the rest of the branches will be skipped.
x = 10
if x > 10:
print("x is greater than 10")
elif x == 10:
print("x is equal to 10")
else:
print("x is less than 10")
This is known as a chained if. The second if will only execute if the first if evaluated as false.
What is the purpose of an else statement in a nested if-else statement?
How many conditions can be checked in a chained if-else statement?
Nested if statements are used when you have an if statement inside another if statement. This allows you to create more complex conditions and control flows.
Each nested if statement is indented to indicate its level within the hierarchy.
x = 10
y = 5
if x > 0:
if y > 0:
print("Both x and y are positive")
else:
print("x is positive, but y is not")
else:
print("x is not positive")
How can we check if a number is greater than 5 using an if statement?
What is the output of the following code?
x= 9
if(x == 10):
print('x is equal to 10')
else:
print('x is not equal to 10')
Which comparison operator is used to check if two numbers are equal?