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.
Operator | Meaning | Example |
---|---|---|
+ | Addition | 2 + 3 |
- | Subtraction | 3 - 2 |
/ | Division | 35 / 5 |
* | Multiplication | 7 * 4 |
Logical operators
Logical operators
Logical operators are used in Python on conditional statements to determine a true or false outcome.
Operator | Meaning | Example |
---|---|---|
and | Checks for both conditions to be true | a>5 and a<10 |
or | Checks for at least one conditions to be true | a>5 or b>10 |
not | Returns false if the result is true | not(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.
- conditional statements such as
if
,else
, andelif
(else if):if
keyword states that if the condition proves to be true, a function is performed. Theelse
keyword catches anything which isnât caught by the preceding conditions. Theelif
or else if keyword is Pythonâs way of saying if the previous conditions were not true, then try this condition. - loops such as the
for
loop and thewhile
loop: Thefor
loop checks for specific conditions and then repeatedly executes a block of code as long as those conditions are met. Thewhile
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
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:
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.
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.
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.
examples
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.
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:
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.
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.
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:
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.
Pass
The pass
statement allows you to run through the loop in its entirety and effectively ignore that the if condition has been satisfied.
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
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
- Under the num_list create a new for loop and print out each value on the list in sequential order.
- 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
- Change the print statement to âOver 45â and add an else condition with a print statement of âUnder 45â.
- 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
- Next, create a new variable called count and assign it a value of 0 and place it outside the for loop.
- Inside the for loop increment the counter by 1.
- Add a print statement outside the for loop to print the value of the count variable.
- Finally, add a break statement directly after the print statement inside the if condition for finding the number.
Use control flow and loops to solve a problem - solution
Solution Code
Step 1
Step 2
Step 3
Step 4
Step 5,6,7
Step 8
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
Previous one â 1.Welcome to Python Programming | Next one â 3.Functions and Data Structures