Python Conditional Statements
Python Conditional Statements
Python code is normally executed in the order in which it is written. However, there comes
a time when we want to execute a specific code if a condition is met. For this, we rely on
conditional statements. Conditional statements first determine whether a specific condition
exists before executing the code. This awards you the ability to control the flow of the
code and have different lines of codes that are executed only when a certain condition is
met. For example, when creating a calculator app, you may want to check which operator
the user entered and execute specific code based on the operator.
If Statement
In python, a conditional statement uses an if-else statement in the following format. The
first code is executed if the condition is true, otherwise, the program moves and executes
the code provided under the else statement.
#syntax for a conditional statement
if condition:
code to execute if true
else:
code to execute otherwise
To build intuition, let’s start working on our calculator. Imagine that we have a python
program that takes three inputs from the user, num1, operator and num2 and returns the
results depending on the operator. For this, we will need to check which operator the user
entered and execute the relevant part of the function.
We must first prompt the user to enter the two numbers and the operator. Please note
that to get user input, we rely on the python built-in input method. Give Google a visit to
learn about it. By default, the input will be a string so we need to cast it to a float using
float(“string”):
#get user input
#get first number
num1 = float(input("Enter first number: ")
#get operator
op = input("Enter operator: ")
#get second number
num2 = float(input("Enter second number: ")
At this point, our program simply requests the user to enter the three different inputs and
assigns them to the relevant operators. Let’s now define our calculator functions. Create
a python file (simpleCalculator.py) in your preferred editor and let’s get cracking.
if-elif-else statement
So far, our calculator can only do two functions, addition and subtraction. If we want to
expand its functionality and make use of the other functions we defined, we will need to
use an “elif statement” — short for else if. This will allow us to check for multiple other
conditions before exiting with an else statement. We will use the last condition (else) for
cases where the user enters an invalid arithmetic sign. See the code:
# define an answer variable to hold our solution
answer = 0
# if addition sign
if op == "+":
# call the add function
answer = add(num1, num2)
# print the results
print(num1, "+", num2, "=", answer)
# if subtraction sign
elif op == "-":
# call the subtract function
answer = subtract(num1, num2)
# print the results
print(num1, "-", num2, "=", answer)
# if multiplication sign
elif op == "*":
# call the multiple function
answer = multiply(num1, num2)
# print the results
print(num1, "*", num2, "=", answer)
# if division sign
elif op == "/":
# call the division function
answer = division(num1, num2)
# print the results
print(num1, "/", num2, "=", answer)
# if modulus sign
elif op == "%":
# call the mod function
answer = mod(num1, num2)
# print the results
print(num1, "%", num2, "=", answer)
# if exponential
elif op == "**":
# call the exp function
answer = exp(num1, num2)
# print the results
print(num1, "^", num2, "=", answer)
# if not a recognized arithmatic sign
else:
print("Invalid operator")
It is also possible to put another “if-elif-else statement” inside another if statement. This
is referred to as a “nested if statement”. In fact, nesting allows you to add multiple if-elif-
else statements inside another if statement. For example, we can modify our code to check
if the second number is not zero to avoid division by zero. Modify the code to be as follows:
elif op == "/":
# if second number is zero
if num2 == 0:
print("Error - division by zero")
else:
# call the division function
answer = division(num1, num2)
# print the results
print(num1, "/", num2, "=", answer)
# if modulus sign
PYTHON LOOPS
Like other programming languages, Python also uses a loop but instead of using a range
of different loops it is restricted to only two loops “While loop” and “for loop”.
• While loops are executed based on whether the conditional statement is true or
false.
• For loops are called iterators, it iterates the element based on the condition set
• Python For loops can also be used for a set of various other things (specifying the
collection of elements we want to loop over)
• Breakpoint is used in For Loop to break or terminate the program at any particular
point
• Continue statement will continue to print out the statement, and prints out the
result as per the condition set
• Enumerate function in “for loop” returns the member of the collection that we are
looking at with the index number
while expression
Statement
Example:
#
#Example file for working with loops
#
x=0
#define a while loop
while(x <4):
print(x)
x = x+1
Output:
0
1
2
3
Just like while loop, “For Loop” is also used to repeat the program.
But unlike while loop which depends on condition true or false. “For Loop” depends on
the elements it has to iterate.
Example:
#
#Example file for working with loops
#
x=0
#define a while loop
#while(x <4):
#print x
#x = x+1
2
3
4
5
6
For Loop iterates with number declared in the range.
For example,
When this code is executed, it will print the number between 2 and 7 (2,3,4,5,6). In this
code, number 7 is not considered inside the range.
For Loops can also be used for a set of other things and not just number. We will see
thin in next section.