Source: Jon Tyson on Unsplash
The if
statement is the fundamental way to execute code conditionally. The code inside the if
block runs only if the condition evaluates to True
.
language = "python"
if language == "python":
print("Language is Python") # This will be executed
if True:
print("This will always print")
if False:
print("This will never print")
Boolean values are True
or False
. Conditional statements rely on expressions that evaluate to a Boolean value.
Common comparison operators:
==
(equal to)!=
(not equal to)>
(greater than)<
(less than)>=
(greater than or equal to)<=
(less than or equal to)is
(object identity)
x = 5
y = 10
print(x == y) # Output: False
print(x != y) # Output: True
print(x < y) # Output: True
The else
statement provides an alternative block of code to execute when the if
condition is False
.
language = "java"
if language == "python":
print("Language is Python")
else:
print("No match") # Output: No match
elif
(else if) allows you to check multiple conditions in sequence.
language = "java"
if language == "python":
print("Language is Python")
elif language == "java":
print("Language is Java") # Output: Language is Java
else:
print("No match")
Boolean operators combine or modify conditions.
and
: Both conditions must be True
.or
: At least one condition must be True
.not
: Negates a condition.
user = "admin"
logged_in = True
if user == "admin" and logged_in:
print("Admin page") # Output: Admin page
if user == "admin" or logged_in:
print("Admin page or logged in") # Output: Admin page or logged in
if not logged_in:
print("Please log in")
is
Keyword)==
checks for equality of values, while is
checks if two variables refer to the same object in memory.
a = [1, 2, 3]
b = [1, 2, 3]
print(a == b) # Output: True (same values)
print(a is b) # Output: False (different objects)
b = a
print(a is b) # Output: True (same object)
print(id(a))
print(id(b))
Certain values implicitly evaluate to False
:
False
None
0
, 0.0
)""
, []
, ()
){}
)Everything else generally evaluates to True
.
condition = ""
if condition:
print("Evaluated to True")
else:
print("Evaluated to False") # Output: Evaluated to False
condition = "test"
if condition:
print("Evaluated to True") # Output: Evaluated to True
else:
print("Evaluated to False")