Imagine you are standing at an intersection. There are 2 roads in front of you and you need to choose one to go along.
Conditional statements in python act as this intersection. It can decide which road you take depending on if it is true or not.
If a conditional statement returns true. It runs, if not, it does not.
In python, conditional statements are if,elif,else.
If - The starting point, ‘what should I do first?’
Elif - The next option, ‘what if the last options doesn't work?’
Else - Last option, ‘if none of the options worked do this’
You can declare them like this:
if {condition}:
{code}
Elif {condition}:
{code}
Else:
{code}
If statements are declared in blocks.
The if statement declares a block.
Inside a block an if condition can only run once. Once run no more if statements will run.
Example:
If {condition}:
Elif {condition}:
When both of these are true. Only the first statement will run. Elif will not run.
However if you have multiple blocks.
Example:
If {condition}:
code
If {condition}:
Code
When both of these are true. The first will check the condition then the second, no matter if it’s true or false
Inside an if block only 1 else can be declared but multiple elif statements can be declared.
Inside a conditional statement, we need to use a comparison operator between 2 values to return either a True or False.
Example
If 5 == 5:
print(‘This will run!’)
If 5 == 6:
print(‘This will not run!’)
Create a simple calculator that asks the user to choose from a menu of operators using numbers 1-4. The calculator keeps the result of the last calculation to keep operating until the user inputs something to make it stop.