Math and logical operators

Operator

An operator is a symbol that tells Python to perform a certain operation.

Operators can be:

  • Mathematical
  • Logical
  • Comparison

Math and logical operators

NOTE

Most of the time, operators work on two values.

Math operators

Math operators

Math operators are used for simple and complex calculations. It’s essentially all the same options as the calculator would have.

OperatorMeaningExample
+Addition2 + 3
-Subtraction3 - 2
/Division35 / 5
*Multiplication7 * 4

Logical operators

Logical operators

Logical operators are used in Python on conditional statements to determine a true or false outcome.

OperatorMeaningExample
andChecks for both conditions to be truea>5 and a<10
orChecks for at least one conditions to be truea>5 or b>10
notReturns false if the result is truenot(a>5)

Control flow: If / else, else if

The flow is represented by the electrical current and the control is the switch itself, with the two states of on and off.

Control flow

Control flow refers to the order in which the instructions in a program are executed. All programs have decisions that need to be made. As a result of this, the program will take different actions or directions.

In Python, there are two types of control flows.

  1. conditional statements such as if, else, and elif (else if): if keyword states that if the condition proves to be true, a function is performed. The else keyword catches anything which isn’t caught by the preceding conditions. The elif or else if keyword is Python’s way of saying if the previous conditions were not true, then try this condition.
  2. loops such as the for loop and the while loop: The for loop checks for specific conditions and then repeatedly executes a block of code as long as those conditions are met. The while loop repeats a specific block of code an unknown number of times until a condition is met.

Conditional statements

This reading introduces you to the conditional statements of if, else and elif.

If

In keeping with the light switch example, the state of the switch can be stored with a Boolean value of True or False.

  • On = True
  • Off = False
#Light is currently off
current = False
 
if current:
    current = False
    print('Turning light off')
 
if not current:
    current = True
    print('Turning light on')

The code snippet above has a variable called current which keeps track of the state of the light - on or off. The first if statement will check if the light is on and if it is, the flow will go inside the condition and set the current variable to False - turning the light off. In the above code snippet, the value of the current variable is initially set to False, so this condition is not met.

The second if statement will check if the light is off and if it is, the flow will go inside the condition and will set the current variable to True - turning the light on.

If else

The above code works fine but it can be rewritten more effectively by using another condition called else. The following code is an example:

current = False
 
if current:
    current = False
    print('Turning light off')
else: 
    current = True
    print('Turning light on')

The else statement has made your code a bit easier to read and given that the flow relates to the same condition, it makes more sense to combine them as part of a single unit.

elif

Python also has another condition called elif which helps when you have multiple conditions to satisfy. The light switch example is pretty straightforward in that you only have to check for the state of on or off - True or False. In certain conditions, it may not be that easy. Thankfully elif is here to help.

Let’s say you want to give a certain discount to customers if they spend over $100. You will also provide an extra discount if that customer is part of a loyalty program. If the customer is not part of the loyalty program and did not spend over a $100, a service charge of 5% is applied.

loyalty_customer = True
total_bill = 124
 
if loyalty_customer and total_bill > 100:
    #give 20% discount
    total_bill = total_bill - (float(total_bill)/ 100) * 20
elif total_bill > 100:
    #give 10% discount
    total_bill = total_bill - (float(total_bill)/ 100) * 10
else:
    #sorry no discount, 5% service charge applied.
    print('Sorry, no discount ...')
 
print('Total Bill: ', float(total_bill))

The above code snippet first checks to see if the customer is part of the loyalty program and if they are spending over 100 and if it is, it will apply a discount of 10% to the bill.

The final else statement is only executed if neither of the other two conditions are met. In this case, a charge of 5% is applied to the bill.


Switch statement

If you have to test a variable against many conditions → match case statement

Conditional statements like if and else work well over a small number of conditions but over a large number of conditions, your code can get large, complex, and messy.

TIP

The match statement In Python was introduced in version 3.10 .

Combining

You can combine several conditions by using the or operator in the conditional statement.

The default is essentially the final outcome if nothing is found in the case checks it’s the equivalent to the else in the if blocks.

http_status = 201
 
if http_status == 200 or http_status == 201:
	print('Success')
elif http_status == 400:
	print('Bad request')
elif http_status == 404:
	print('Not Found')
elif http_status == 500 or http_status == 501:
	print('Server Error')
else:
	print('Unknown')
 
 
match http_status:
	case 200 | 201:
		print('Success')
	case 400:
		print('Bad Request')
	case 500 | 501:
		print('Server Error')
	case _:
		print('Unknown')

Match statement

A match statement compares a value to several different conditions until one is met.


Looping constructs

The same set of steps must be carried out many times → Loops

Python has two different types of looping constructs for iterating over sequences:

  • for
  • while

INFO

Looping is used to iterate through the sequence and access each item inside the sequence.

First, you declare a variable called str, which is of type string, recall that a string in Python is a sequence, which means you can iterate over each character in the string. A sequence is just an ordered set.

str = 'Looping'
for item in str:
	print(item)
L
o
o
p
i
n
g

examples

for i in range(10):
	print('Looping ...', i)
Looping ... 0
Looping ... 1
Looping ... 2
Looping ... 3
Looping ... 4
Looping ... 5
Looping ... 6
Looping ... 7
Looping ... 8
Looping ... 9
favorites = ['Creme Brulee', 'Apple Pie', 'Churros', 'Tiramisu', 'Chocolate Cake']
 
for item in favorites:
	print('I like this desert', item)
I like this desert Creme Brulee
I like this desert Apple Pie
I like this desert Churros
I like this desert Tiramisu
I like this desert Chocolate Cake
favorites = ['Creme Brulee', 'Apple Pie', 'Churros', 'Tiramisu', 'Chocolate Cake']
 
count = 0
 
while count < len(favorites):
	print('I like this desert', favorites[count])
		count += 1
I like this desert Creme Brulee
I like this desert Apple Pie
I like this desert Churros
I like this desert Tiramisu
I like this desert Chocolate Cake
favorites = ['Creme Brulee', 'Apple Pie', 'Churros', 'Tiramisu', 'Chocolate Cake']
 
for idx, item in enumerate(favorites):
	print(idx, item)
0 Creme Brulee
1 Apple Pie
2 Churros
3 Tiramisu
4 Chocolate Cake

Looping Constructs: Practical Examples

For loop

Looping through data is a fairly common task in any programming language. The for loop makes it easy to work with any type of sequence in Python. Let’s run through some examples of for loops and the different ways you can use them.

favorites = ['Creme Brulee', 'Apple Pie', 'Churros', 'TiramisĂș', 'Chocolate Cake']
 
for dessert in favorites:
    print('One of my favorite desserts is', dessert)

In the code snippet above, the for loop iterates over the contents of the favorites list and prints out a sentence with the dessert name for each item in the list.

The for loop is based on the size or length of the elements to iterate over.

While loop

On the other hand, a while loop is based upon a condition being true. Once the condition is no longer true the loop stops. The amount of times the while loop is executed is not known ahead of time as it is with the for loop.

If you take the above for loop example and convert that to the while loop alternative, you will end up with something like this:

favorites = ['Creme Brulee', 'Apple Pie', 'Churros', 'TiramisĂș', 'Chocolate Cake']
 
count = 0
 
while count < len(favorites):
    print('One of my favorite desserts is', favorites[count]);
    count += 1

Note that you needed to declare a counter variable. The counter variable is then compared to the length of the favorites list. As you loop through the data the counter is incremented. Once the condition count < len(favorites) is no longer true the loop will stop.


Practicing control flow and loops

Controlling loops

So far, you have only looped over sequences based on the length of the data you wanted to iterate over. In many cases, this is not necessary and depending on the amount of the data it can also be quite costly. You’ll now examine how you can control the flow of the loop and exit out when a specific condition is met. You will also look at control statements such as break, continue and pass.

If else

In many cases, you may need to search for a particular item in a list. Once the item is found, there is no need to continue looping over the other results. Using the same example as before, let’s assume you only need to check if the dessert “Churros” is in the list and if it is, print a single statement.

#Starter Code
favorites = ['Creme Brulee', 'Apple Pie', 'Churros', 'TiramisĂș', 'Chocolate Cake']
 
for dessert in favorites:
    if dessert == 'Churros':
        print('Yes! One of my favorite desserts is', dessert)        

Running the above code will output the following:

Yes! One of my favorite desserts is Churros

But what happens if you look for a dessert and that dessert is not on the list? The code above is currently not set up to handle this. Let’s look for the dessert “Pudding” which is not on the list, and also add an else statement to handle the case of when it’s not found. If the dessert is not part of the list, you will print a new statement.

#Starter Code
favorites = ['Creme Brulee', 'Apple Pie', 'Churros', 'TiramisĂș', 'Chocolate Cake']
 
for dessert in favorites:
    if dessert == 'Pudding':
        print('Yes one of my favorite desserts is', dessert) 
    else:
        print('No sorry, that dessert is not on my list')

Running the above code will result in the following output:

No sorry, that dessert is not on my list

Loop control statements

Break

The code works as intended but you may notice one flaw. If you change the search term to something that is on the list like “Churros” and run it again you will get the following output:

Yes one of my favorite desserts is Churros No sorry, not a dessert on my list

This is not what you want! The dessert is on the list but it still printed out the else condition. To fix it, you need to use a control statement called break.

Add the following:

#Starter Code
favorites = ['Creme Brulee', 'Apple Pie', 'Churros', 'TiramisĂș', 'Chocolate Cake']
 
for dessert in favorites:
    if dessert == 'Pudding':
        print('Yes one of my favorite desserts is', dessert)
        break 
    else:
        print('No sorry, not a dessert on my list')

Running the above code will resolve the issue. The break statement is used to stop the loop, which in turn also stops the else condition. Without the break the loop will continue even after the if condition is satisfied.

Continue

Similar to break, continue can be used to control the iteration of the loop. The key difference is that it can allow you to skip over a section of the loop but then continue on with the rest. If you change your code to this, you will notice the outcome will print everything except the Churros dessert.

#Starter Code
favorites = ['Creme Brulee', 'Apple Pie', 'Churros', 'TiramisĂș', 'Chocolate Cake']
 
for dessert in favorites:
    if dessert == 'Churros':
        continue
    print('Other desserts I like are', dessert) 

Pass

The pass statement allows you to run through the loop in its entirety and effectively ignore that the if condition has been satisfied.

#Starter Code
favorites = ['Creme Brulee', 'Apple Pie', 'Churros', 'TiramisĂș', 'Chocolate Cake']
 
for dessert in favorites:
    if dessert == 'Churros':
        pass
    print('Other desserts I like are', dessert) 

Nested loops and the effect on algorithmic complexity

Python nested loops can be used to solve more complex problems. For example, the nested for-loop is written by indentation inside the outer loop.

Examples

#outer loop
for i in range(10):
	#inner loop
	for j in range(10):
		print(0, end=" ")
	print()
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
import time
start_time = time.time()
 
#outer loop
for i in range(2):
	#inner loop
	for j in range(10):
		print(0, end = " ")
	print()
 
print(round((time.time() - start_time), 2))
0.0
But if you increase numbers in the `range()`, the time also increases too much

TIP

Since there will be so many decimal numbers, the round function is used to just show some of them, 2 in this case.

TIP

The larger the array or the larger the range, in this case, the more time it’s going to take for a program to complete. It’s always important to remember how you can optimize code to make it run more efficiently.


Exercise: Use control flow and loops to solve a problem

Introduction

In this exercise, you will practice control flow with loops to solve problems. You will be given a list of integers and you will have to add some code to find a specific number in a list and return it.

Instructions

  1. Under the num_list create a new for loop and print out each value on the list in sequential order.
  2. Inside the for loop, create a condition that will look for all numbers that are greater than 45 and print out only numbers that meet that condition
  3. Change the print statement to “Over 45” and add an else condition with a print statement of “Under 45”.
  4. Update the for loop to use the enumerate function so you can get and use the index. Alter the condition to look for number 36 and print out the following: ‘Number found at position: ‘, index number
  5. Next, create a new variable called count and assign it a value of 0 and place it outside the for loop.
  6. Inside the for loop increment the counter by 1.
  7. Add a print statement outside the for loop to print the value of the count variable.
  8. Finally, add a break statement directly after the print statement inside the if condition for finding the number.
num_list = [33,42,5,66,77,22,16,79,36,62,78,43,88,39,53,67,89,11]
for num in num_list:
    if num > 45:
        print(num, end = " ")
    else:
        print()
        print('Under 45!')

Use control flow and loops to solve a problem - solution

Solution Code

Step 1

num_list = [33,42,5,66,77,22,16,79,36,62,78,43,88,39,53,67,89,11]
 
for num in num_list:
    print(num)

Step 2

num_list = [33,42,5,66,77,22,16,79,36,62,78,43,88,39,53,67,89,11]
 
for num in num_list:
    if num > 45:
        print(num)

Step 3

num_list = [33,42,5,66,77,22,16,79,36,62,78,43,88,39,53,67,89,11]
 
for num in num_list:
    if num > 45:
        print('Over 45')
    else:
        print('Under 45')

Step 4

num_list = [33,42,5,66,77,22,16,79,36,62,78,43,88,39,53,67,89,11]
 
for x,num in enumerate(num_list):
    if num == 36:
        print('Number found at ', x)

Step 5,6,7

num_list = [33,42,5,66,77,22,16,79,36,62,78,43,88,39,53,67,89,11]
 
count = 0
 
for x,num in enumerate(num_list):
    count += 1
    if num == 36:
        print('Number found at ', x)
 
print(count)

Step 8

num_list = [33,42,5,66,77,22,16,79,36,62,78,43,88,39,53,67,89,11]
 
count = 0
 
for x,num in enumerate(num_list):
    count += 1
    if num == 36:
        print('Number found at ', x)
        break
 
print(count)

Additional resources

Access the links below to learn more about programming in Python.

Explore the Python website to learn more about control flow: Learn more about Python

Check out W3Scools to learn more about Conditional Operators: W3Schools

Learn more about conditional statements at the Real Python website: realpython.com


flowconditionloopPython

Previous one → 1.Welcome to Python Programming | Next one → 3.Functions and Data Structures