If Statement
Part of the Fundamentals section of Coddy's Python journey — lesson 20 of 77.
If statements allow us to execute code with conditions.
For example, let's look at the following code:
age = 20
status = "Child"
if age > 18:
status = "Adult"
age += 1The above code checks whether the age variable is greater than 18. If it is, it will set status to hold "Adult" string.
In the end, the code will increment age by 1 whether the age is greater than 18 or not.
To use an if statement, we need to add a colon : at the end of the if, and everything that is inside the if is indented with 4 spaces or tab:
if condition:
code
code
codeIf the condition is True, we will enter the code block inside the if (the indented code).
Challenge
BeginnerThe variables a and b have missing values, fill them so that the code inside the if statement will be executed! (make sure the if condition is true)
At the end of the program, the value of c should be 3.
Bonus: try to find more than one solution!
Cheat sheet
If statements in Python allow conditional execution of code:
if condition:
# Indented code block
# Executed if condition is TrueKey points:
- Use a colon
:after the condition - Indent the code block with 4 spaces or a tab
- The indented code executes only if the condition is
True
Example:
age = 20
status = "Child"
if age > 18:
status = "Adult"
age += 1In this example, status becomes "Adult" because age is greater than 18.
Try it yourself
a = ?
b = ?
# Don't change below this line
c = 0
if a >= b and not b < 10:
c = 2
c += 1
print(f"c = {c}")This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
4Operators Part 2
Logical Operators Part 1Logical Operators Part 2Recap - Simple LogicLogical Operators Part 3Logical Operators Part 48Loops
For LoopWhile LoopBreakContinueRecap - FactorialThe Range FunctionNested LoopRecap - Dynamic Input3Operators Part 1
Arithmetic OperatorsModulo OperatorArithmetic ShortcutsRecap - Simple MathComparison Operators9Functions
Declare a FunctionArgumentsReturnRecap - Sigma FunctionRecap - Validation FunctionDefault Values12Iterating Over Sequences
Iterating Over ElementsThe Enumerate FunctionIterating Over Strings Part 1Iterating Over Strings Part 2