- If Statements Explained
- Introduction
- Indentation and Blocks
- If-Else
- Elif
- Exercise
- Python if any statement
- # Table of Contents
- # Check if ANY element in a list meets a condition in Python
- # Getting the element that meets the condition
- # Check if ANY element in a list meets a condition using a for loop
- # Check if ALL elements in a List meet a condition in Python
- # Check if ALL elements in a List meet a condition using a for loop
- # Additional Resources
- Python if any statement
- # Check for multiple conditions in an if statement in Python
- # Using the all() function to check for multiple conditions in if
- # Check for multiple conditions using boolean OR
If Statements Explained
A program sometimes may have to make choices. These choices can execute different code depending on certain condition.
In Python the if statement is used for conditional execution or branching. An if statement is one of the control structures. (A control structure controls the flow of the program.)
Introduction
In the example below we show the use if statement, a control structure. An if statement evaluates data (a condition) and makes a choice.
Lets have al look at a basic if statement. In its basic form it looks like this:
- is the condition evaluated as a Boolean, it can either be True or False.
- is one more lines of code. Each of those lines must indented with four spaces.
Several examples of the if statements are shown below, you can run them in the Python interpreter:
#!/usr/bin/env python3
>>> x = 3
>>> if x < 10:
. print(‘x below ten’)
.
x below ten
>>> if x > 10:
. print(‘x is greater than ten’)
.
>>> if x > 1 and x < 4:
. print(‘x is in range’)
.
x is in range
>>>
It’s very important to have four spaces for the statements. Every if statement needs a colon.
More than one condition can be combined using the and keyword.
Indentation and Blocks
An if statement doesn’t need to have a single statement, it can have a block. A block is more than one statement.
The example below shows a code block with 3 statements (print). A block is seen by Python as a single entity, that means that if the condition is true, the whole block is executed (every statement).
#!/usr/bin/env python3
x = 4
if x < 5:
print(«x is smaller than five»)
print(«this means it’s not equal to five either»)
print(«x is an integer»)
All programming languages can create blocks, but Python has a unique way of doing it. A block is defined only by its indention.
Other programming languages often used symbols like < , >or words begin and end .
So the basic form of a Python if statement block is:
After completing the if statement, Python continues execution of the program. The if statement ends by its indetion, it goes back four spaces.
Visual example of if statement (click to enlarge):
If-Else
You can use if statements to make an interactive program. Copy the program below and run it.
It has several if statements, that are evaluated based on the keyboard input.
Because keyboard input is used, we use the equality sign (==) for string comparison.
The second string is typed, but we need a number. You can convert the string to an integer using int().
It also makes use of the else keyword, this is the other evaluation case. When comparing age (age < 5) the else means (>= 5), the opposite.
#!/usr/bin/env python3
gender = input(«Gender? «)
gender = gender.lower()
if gender == «male»:
print(«Your cat is male»)
elif gender == «female»:
print(«Your cat is female»)
else:
print(«Invalid input»)
age = int(input(«Age of your cat? «))
if age < 5:
print(«Your cat is young.»)
else:
print(«Your cat is adult.»)
Elif
If you want to evaluate several cases, you can use the elif clause. elif is short for else if. Unlike else with elif you can add an expression.
That way instead of writing if over and over again, you can evaluate all cases quickly.
>>> x = 3
>>> if x == 2:
. print(‘two’)
. elif x == 3:
. print(‘three’)
. elif x == 4:
. print(‘four’)
. else:
. print(‘something else’)
.
three
>>>
This is a more elegant and Pythonic than to write a list of if-statements as shown below.
x = 3
if x == 2:
print(‘two’)
if x == 3:
print(‘three’)
if x == 4:
print(‘four’)
But comes down to the same thing, the only difference is the syntax (and readablity).
Exercise
1\. Make a program that asks the number between 1 and 10\.
If the number is out of range the program should display «invalid number».
2\. Make a program that asks a password.
Once completed continue with the next exercise.
How to read keyboard-input?
Python «for» Loops (Iteration Introduction)
Python if any statement
Last updated: Feb 20, 2023
Reading time · 5 min
# Table of Contents
# Check if ANY element in a list meets a condition in Python
Use the any() function to check if any element in a list meets a condition.
The any function will return True if any element in the list meets the condition and False otherwise.
Copied!my_list = [1, 3, 5, 15] if any(item > 10 for item in my_list): # 👇️ this runs print('There is an item greater than 10') else: print('No items in the list are greater than 10') # 👇️ True print(any(item > 10 for item in my_list)) # 👇️ False print(any(item > 50 for item in my_list))
If you need to check if ALL elements in a list meet a condition, click on the following subheading:
The any function takes an iterable as an argument and returns True if any element in the iterable is truthy.
We passed a generator expression to the any() function.
Generator expressions are used to perform some operation for every element or select a subset of elements that meet a condition.
In the example, we check if each item in the list is greater than 10 and return the result.
# Getting the element that meets the condition
You can use the assignment expression syntax if you need to get the element that meets the condition.
Copied!my_list = [1, 3, 5, 15] if any((match := item) > 10 for item in my_list): # 👇️ this runs print('There is an item greater than 10') print(match) # 👉️ 15 else: print('No items in the list are greater than 10')
Assignment expressions allow us to assign to variables within an expression using the NAME := expression syntax.
If the condition is met at least once, the any() function returns True .
If the iterable we pass to the any() function is empty or none of the elements in the iterable are truthy, the any function returns False .
Copied!my_list = [1, 3, 5] if any(item > 10 for item in my_list): print('There is an item greater than 10') else: # 👇️ this runs print('No items in the list are greater than 10')
None of the items in the list is greater than 10 , so the condition is never met and any() returns False .
If your list is empty, the any function will always return False .
Copied!my_list = [] if any(item > 10 for item in my_list): print('There is an item greater than 10') else: # 👇️ this runs print('No items in the list are greater than 10')
Here is another example that uses the any() function to check if at least 1 item in the list has a None value.
Copied!my_list = ['a', 'b', None, 'd'] if any(item is None for item in my_list): # 👇️ This runs print('There is a None value in the list') else: print('No items in the list have a value of None') # 👇️ True print(any(item is None for item in my_list))
The generator expression we passed to the any() function iterates over the list and checks if each value is None.
If the condition is met at least once, the any function returns True , otherwise, it returns False .
# Check if ANY element in a list meets a condition using a for loop
You can also use a for loop to check if any element in a list meets a condition.
Copied!my_list = [1, 3, -4, 5, 15, -3] any_meets_condition = False for element in my_list: if element > 10: any_meets_condition = True print(element) # 👉️ 15 break print(any_meets_condition) # 👉️ True
We used a for loop to iterate over the list
On each iteration, we check if the current element is greater than 10 .
If the condition is met, we set the any_meets_condition variable to True and exit the loop.
You also have access to the element that meets the condition in the if block.
# Check if ALL elements in a List meet a condition in Python
Use the all() function to check if all elements in a list meet a condition.
The all function will return True if all elements in the list meet the condition and False otherwise.
Copied!my_list = [1, 3, 5, 15] if all(item > 0 for item in my_list): # 👇️ this runs print('All elements in the list are greater than 0') else: print('Not all elements in the list are greater than 0') # 👇️ True print(all(item > 0 for item in my_list)) # 👇️ False print(all(item > 10 for item in my_list))
The all() built-in function takes an iterable as an argument and returns True if all elements in the iterable are truthy (or the iterable is empty).
We passed a generator expression to the all() function.
Generator expressions are used to perform some operation for every element or select a subset of elements that meet a condition.
In the example, we check if all elements in the list are greater than 0 .
The all function will return True if all elements in the list meet the condition and False otherwise.
If a single value that doesn’t meet the condition is encountered, the all() function short-circuits returning False .
# Check if ALL elements in a List meet a condition using a for loop
You can also use a basic for loop to check if all elements in a list meet a condition.
Copied!my_list = [1, 3, 5, 15] all_meet_condition = True for element in my_list: if element 0: all_meet_condition = False break print(all_meet_condition) # 👉️ True
We initialized a variable to True and used a for loop to iterate over the list.
On each iteration, we check if the current item is less than 0 .
If the condition is met, we set the all_meet_condition variable to False and break out of the loop.
If the condition is never met, the all_meet_condition variable remains set to True .
The break statement breaks out of the innermost enclosing for or while loop.
You can also use this approach to get the elements that don’t meet the condition or to get the ones that do.
Copied!my_list = [1, 3, -4, 5, 15, -3] all_meet_condition = True meet_condition = [] dont_meet_condition = [] for element in my_list: if element 0: all_meet_condition = False dont_meet_condition.append(element) else: meet_condition.append(element) print(all_meet_condition) # 👉️ False print(meet_condition) # 👉️ [1, 3, 5, 15] print(dont_meet_condition) # 👉️ [-4, -3]
We used a for loop to iterate over the list.
On each iteration, we check if the current element is less than 0 .
If the condition is met, we append the value to the dont_meet_condition list.
Otherwise, the value is appended to the meet_condition list.
# Additional Resources
You can learn more about the related topics by checking out the following tutorials:
I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
Python if any statement
Last updated: Feb 18, 2023
Reading time · 4 min
# Check for multiple conditions in an if statement in Python
Use the boolean and operator to check for multiple conditions in an if statement.
The if block will only run if all of the conditions are met.
Copied!a = 1 b = 3 c = 7 # ✅ check for multiple conditions using AND if a == 1 and b == 3 and c == 7: # 👇️ this runs print('All conditions in the if statement are met') else: print('Not all conditions in the if statement are met') # -------------------------------------------- # ✅ check for multiple conditions using OR if a == 10 or b == 30 or c == 7: # 👇️ this runs print('One or more conditions in the if statement are met') else: print('None of the conditions in the if statement is met')
The first example uses the boolean and operator to check for multiple conditions in an if statement.
You can use any of the comparison operators in the conditions.
Copied!a = 1 b = 3 c = 7 if a > 0 and b > 0 and c > 0: # 👇️ this runs print('All conditions in the if statement are met') else: print('Not all conditions in the if statement are met')
The example checks if the variables a , b and c store values that are greater than 0 .
If any of the conditions evaluates to False , the interpreter short-circuits and doesn’t evaluate the next conditions.
# Using the all() function to check for multiple conditions in if
Alternatively, you can use the all() function.
Copied!a = 1 b = 3 c = 7 if all([a > 0, b > 0, c > 0]): # 👇️ this runs print('All conditions in the if statement are met') else: print('Not all conditions in the if statement are met')
We passed a list containing multiple conditions to the all() function.
The all() built-in function takes an iterable as an argument and returns True if all elements in the iterable are truthy (or the iterable is empty).
If all of the conditions in the list evaluate to True , the if block runs, otherwise, the else block runs.
If one of the conditions isn’t met, the all() function will short-circuit and the else block will run.
# Check for multiple conditions using boolean OR
If you need to check if at least one condition is met, use the boolean OR operator.
The if block will run if at least one of the conditions is met.
Copied!a = 1 b = 3 c = 7 # ✅ check for multiple conditions using OR if a == 10 or b == 30 or c == 7: # 👇️ this runs print('One or more conditions in the if statement are met') else: print('None of the conditions in the if statement is met')