This is part of “An intro to Python” series of posts, with content from the Enki app. If you stumbled upon this, you can start from the beginning.
Control flow is the order in which individual statements or functions are executed. Control flow statements give choices that result in different outcomes.
The if…else statement is used in Python for this decision making.
The program will only execute the code if the condition has been met.
The code above will print ’3 is a positive number’.
The if statement can be extended to include a catch-all, else, that will be executed if the condition is not met.
The code above will print ’Negative number’.
As you may have spotted, we can use comparison operators to create conditions in Python.
Comparison operators include:
Note that a single = is used for assigning values to variables, not for comparison.
What if we want to change the behavior of our program based on multiple conditions?
We can add another if into our if…else statement!
In terms of syntax, this is written as elif. It’s shorthand for else if.
If the condition for if has not been met, the program will check the elif. If it meets this condition it will execute the elif body of code.
The else code is only executed if none of the other conditions have been met.
If we assign the value 0 to num, our program above will print ’Zero’.
There is no limit to how many elif statements you can write.
It’s time to test your Python knowledge! Go to the playground and replace all the ??? such that You're at the start of a great journey! is printed.