Python
|
if statements
The if statement evaluates expressions to either True or False and executes different code blocks accordingly.
If the expression evaluates to True, then the code block of the if statement will be executed.
Basic if statement structure:
Values that evaluate to False by default:
These values evaluate to False:
None, False, 0, 0.0, '' (empty string), [] (empty list), () (empty tuple), {} (empty dictionary), set() (empty set)
Simple if statements:
if-else statements:
if-elif-else statements:
Nested if statements:
Better Practices for None Comparisons:
The not operator:
Ternary operator (conditional expression):
Equality operator (==):
Inequality operator (!=):
Comparison operators:
Logical and operator:
Logical or operator:
Complex conditions with parentheses:
Membership operator (in):
Checking if a value is in a list.
Checking if a value is in a dictionary.
Checking if a value is in a string.
Negative membership operator (not in):
Checking if a value is not in a list.
Checking if a value is not in a dictionary.
Checking if a value is not in a string.
Checking if a list is empty:
Using if statements with any/all methods: