If Else Statement in Python
An if else
statement in Python is used to execute different blocks of code based on whether a specific condition is true or false. It allows a program to respond differently to different situations or inputs. Here’s a basic structure:
pythonCopy codeif condition:
# code to execute if the condition is true
else:
# code to execute if the condition is false
The
condition
is any expression that evaluates toTrue
orFalse
.If the
condition
isTrue
, the code block under theif
clause runs.If the
condition
isFalse
, the code under theelse
clause runs instead.
Here’s a simple example:
pythonCopy codeage = 20
if age >= 18:
print("You are an adult.")
else:
print("You are a minor.")
In this example, the program will print "You are an adult." because the condition age >= 18
is true. If age
were less than 18, it would print "You are a minor."
Learn more with the free online Python tutorial and use the free online Python editor to grow in your tech journey!