Python If-Else Statements

In Python, if statements are used to test a condition and execute a block of code if the condition is true. If the condition is false, the code inside the if statement will not be executed.

The if Statement

The if statement is the simplest form of conditional statement in Python. The basic syntax is as follows:

1if condition: 2 # code to be executed if condition is True

For example, the following code will print "Hello, World!" if the x variable is greater than 0:

1x = 1 2if x > 0: 3 print("Hello, World!")

The if-else Statement

The if-else statement allows you to execute one block of code if the condition is true, and another block of code if the condition is false. The basic syntax is as follows:

1if condition: 2 # code to be executed if condition is True 3else: 4 # code to be executed if condition is False

The condition can be any expression that evaluates to a Boolean value (True or False). If the condition is True, the code in the if block will be executed, otherwise, the code in the else block will be executed.

For example, the following code will print "Hello" if x is even, and "World" if x is odd:

1x = 3 2if x % 2 == 0: 3 print("Hello") 4else: 5 print("World")

The if-elif-else Statement

The if-elif-else statement allows you to check multiple conditions and execute different code blocks depending on the condition that is true. The basic syntax is as follows:

1if condition1: 2 # code to be executed if condition1 is True 3elif condition2: 4 # code to be executed if condition2 is True 5else: 6 # code to be executed if all conditions are False

For example, the following code will print "A" if x is 1, "B" if x is 2, and "C" if x is anything else:

1x = 3 2if x == 1: 3 print("A") 4elif x == 2: 5 print("B") 6else: 7 print("C")

Nested if Statements

You can also use nested if statements to test multiple conditions. This means that you can put an if statement inside another if statement. The basic syntax is as follows:

1if condition1: 2 # code to be executed if condition1 is True 3 if condition2: 4 # code to be executed if both condition1 and condition2 are True

For example, the following code will print "A" if x is 1 and y is greater than 0, and "B" otherwise:

1x = 1 2y = 2 3if x == 1: 4 if y > 0: 5 print("A") 6 else: 7 print("B") 8else: 9 print("B")