Python Logo

If...Else


If and if...else conditions are conditional statements that allow you to control the flow of your code based on the evaluation of a condition.

If conditions are used to execute a block of code if a condition is True. The syntax for an if condition is as follows:

 

Python

if condition:
  code block
 

The condition can be any Boolean expression. If the condition evaluates to True, the code block is executed. If the condition evaluates to False, the code block is skipped.

Examples:

 

Python

# Check if a number is even
number = 10
if number % 2 == 0:
  print("The number is even.")

# Check if a string is empty
string = ""
if string:
  print("The string is not empty.")
else:
  print("The string is empty.")

# Check if a list is empty
my_list = []
if my_list:
  print("The list is not empty.")
else:
  print("The list is empty.")
 

If...else conditions are used to execute different blocks of code depending on the evaluation of a condition. The syntax for an if...else condition is as follows:

 

Python

if condition1:
  code block 1
elif condition2:
  code block 2
...
else:
  code block n
 

The condition1, condition2, ..., conditionn can be any Boolean expressions. If the first condition evaluates to True, the code block 1 is executed and the rest of the conditions are not evaluated. If the first condition evaluates to False, the second condition is evaluated. If the second condition evaluates to True, the code block 2 is executed and the rest of the conditions are not evaluated. This process continues until a condition evaluates to True or all of the conditions have been evaluated and none of them evaluated to True. If none of the conditions evaluate to True, the code block n is executed.

Examples:

 

Python

# Check if a number is positive, negative, or zero
number = 5
if number > 0:
  print("The number is positive.")
elif number < 0:
  print("The number is negative.")
else:
  print("The number is zero.")

# Check if a string is uppercase, lowercase, or mixed case
string = "Hello, World!"
if string.isupper():
  print("The string is uppercase.")
elif string.islower():
  print("The string is lowercase.")
else:
  print("The string is mixed case.")

# Check if a list is empty, has one element, or has more than one element
my_list = [1, 2, 3]
if my_list:
  if len(my_list) == 1:
    print("The list has one element.")
  else:
    print("The list has more than one element.")
else:
  print("The list is empty.")
 

If and if...else conditions are powerful tools that allow you to control the flow of your code in a variety of ways. By understanding how to use if and if...else conditions, you can write more efficient and readable code.