False
Comparison operators are used to compare two values or expressions. They return a Boolean value: True or False.
The common comparison operators in Python include:
==
: Equal to!=
: Not equal to>
: Greater than<
: Less than>=
: Greater than or equal to<=
: Less than or equal toEqual to and Not Equal to
if
elif
else
This is what the syntax of conditional statements looks like:
Example: If-Else Statement
This code checks the temperature. If it’s greater than 25, it prints that it’s a hot day; otherwise, it prints a different message.
Example: If-Elif-Else Statement
The following code evaluates the score and prints the corresponding grade based on the defined ranges.
We can use elif
statements when we want to check multiple conditions that are dependent on each other.
In that case, only one block should be executed among multiple conditions
The elif
block will be checked if the preceding if
or elif
conditions were false
if
and elif
if
and elif
Use if
:
if
and elif
Use elif
:
elif
block will be checked only if the preceding if
and elif
conditions were falseif
vs. elif
if
(independent conditions)Take an umbrella.
if the weather is rainy, it will print “Take an umbrella.”
the other conditions will still be checked, but only the block for the true condition will execute.
if
vs. elif
elif
(dependent conditions)Take an umbrella.
only the block for the first condition will execute
if weather
is “rainy”, it will print “Take an umbrella.” and then skip all subsequent elif
blocks.
if
vs. elif
Using elif
(dependent conditions)
Here is when elif
gets executed
Wear a windbreaker.
elif
block will be checked only if the preceding if
and elif
conditions were falseelse
statementThe else
statement can be used to define a block of code to be executed if none of preceding if
or elif
conditions are true.
It is a catch-all for any cases not covered by previous conditions
Thus, use else
when you want to specify a block fo code if the preceding conditions are false.
else
statementweather = "rainy"
if weather == "rainy":
print("Take an umbrella.")
elif weather == "windy":
print("Wear a windbreaker.")
elif weather == "sunny":
print("Wear sunglasses.")
else:
print("Check weather & dress well")
Take an umbrella.
The if
statement checks if the weather is “rainy”. If true, it prints “Take an umbrella.”.
The first elif
checks if the weather is “windy”. If true, it prints “Wear a windbreaker.” but only if the previous if
condition was false.
The second elif
checks if the weather is “sunny”. If true, it prints “Wear sunglasses.” but only if all previous conditions were false.
else
statementweather = "rainy"
if weather == "rainy":
print("Take an umbrella.")
elif weather == "windy":
print("Wear a windbreaker.")
elif weather == "sunny":
print("Wear sunglasses.")
else:
print("Check weather & dress well")
Take an umbrella.
else
statement catches any other weather conditions not covered by the if and elif statements and prints “Check weather & dress well”.Write a program using if
, elif
, and else
that prints a letter grade for students.
Here are the rules:
Let’s start with grade=92
This is how we can wite this:
Note that you could potentially write this only with if
statements.
This however would require checking each condition independently.
This approach is less efficient as it does not take advantage of the mutual exclusive nature of the elif
conditions.
What if the grade was 72?
What if the grade was 72?
try
and except
Error handling allows us to deal with errors during code execution without crashing the program.
It’s essential to make programs more robust and user-friendly.
Why Use try and except?
try
to test a block of code for errors.handle
the error if one occurs.try
and except
This the basic syntax:
Example:
10.0
try
and except
try
fails.You can have multiple except
blocks to handle different types of errors.
We will learn how to store more than one value in a variable
Lists are collection of items that are stored in variable
The following is a list:
We can access items in a list in the following way:
We can access the second item in the following way:
Thus, notice that item enumeration starts from 0.
We can get the last item of a list in the following way
We can get the second the last item from a list
Store the values ‘python’, ‘c’, and ‘java’ in a list. Print each of these values out, using their position in the list.
Store the values ‘python’, ‘c’, and ‘java’ in a list. Print each of these values out, using their position in the list.
Store the values ‘John’, ‘Anna’, and ‘Emma’ in a list. Print a statement about each of these values, using their position in the list.
Your statement could simply be, ‘A student in this class is value.’
Store the values ‘John’, ‘Anna’, and ‘Emma’ in a list. Print a statement about each of these values, using their position in the list.
Your statement could simply be, ‘“Value” is one of the students taking the class.’
A loop is used to execute a given code section more than once.
A for
loop is composed of:
for
keywordin
keywordThis is the syntax in a for
loop
Here is another example with strings:
for
loop to iterate through the vector and print each element.The output should look like below:
1, 1
2, 4
3, 9
4, 16
5, 25
6, 36
7, 49
8, 64
9, 81
10, 100
for
loop to iterate through the vector and print each element.The output should look like below:
1, 1.0
2, 1.7320508075688772
3, 2.23606797749979
4, 2.6457513110645907
5, 3.0
6, 3.3166247903554
7, 3.605551275463989
8, 3.872983346207417
list_students = ["John", "Anna", "Emma"]
for
loop to iterate through the vector and write:John is one of the students taking the class. Anna is one of the students taking the class. Emma is one of the students taking the class.
list_students = ["John", "Anna", "Emma"]
for
loop to iterate through the vector and write:John is one of the students taking the class.
Anna is one of the students taking the class.
Emma is one of the students taking the class.
We can use the function break
to interrupt a loop.
When a condition is met, the loop will stop.
The break
function could also make a piece of code more efficient: our code runs quicker.
The use of break is even more apparent in the following case:
In this case, we were trying to find number that could be divided by both 3 and 7.
Rather than going though the whole range from 1 to 100, the loop stops when it first encounters a number that is divisible by both 3 and 7.
When looping though a list, it may often be necessary to identify the index of a current item.
The enumerate()
function takes the index and then it loops through the list.
For example:
list_students = ["John", "Anna", "Emma"]
for index, student in enumerate(list_students):
place = str(index)
print("Place: " + place + " Student: " + student)
Place: 0 Student: John
Place: 1 Student: Anna
Place: 2 Student: Emma
the index variable holds the index which is an integer
if you want to print it in a string, the integer needs to be turned into a string
as before, the integer always starts at 0.
zip()
functionThe zip()
function takes multiple iterables (such as lists, tuples, or strings) and aggregates them into tuples.
A tuple - an immutable (unable to be changed), ordered collection of elements that can hold multiple items.
It creates an iterator of tuples, where the i-th tuple contains the i-th element from each iterable.
The first item in each passed iterator is paired together.
The second item in each passed iterator is paired together, etc.
zip()
functionHere is an example:
zip()
functionWe can also use the plus-equals operator.
The plus-equals operator +=
provides a convenient way to add a value to an existing variable
This assigns the new value back to the same variable.
list_students = ["John", "Anna", "Emma"]
list_grades = [89, 51, 70]
count = 0
for student, grade in zip(list_students, list_grades):
count += 1
print("Student " + str(count) + ": " + student + " obtained " + str(grade) + " in the exam.")
Student 1: John obtained 89 in the exam.
Student 2: Anna obtained 51 in the exam.
Student 3: Emma obtained 70 in the exam.
zip()
function ExerciseSuppose that you want to increase the grade for John, Anna, and Emma by 5%.
Use the previous code to update the grades by 5%.
zip()
function Exercise solutionSuppose that you want to increase the grade for John, Anna, and Emma by 5%.
Use the previous code to update the grades by 5%.
list_students = ["John", "Anna", "Emma"]
list_grades = [89, 51, 70]
count = 0
for student, grade in zip(list_students, list_grades):
count += 1
updated_grade = grade + grade * 5/100
print("Student " + str(count) + ": " + student + " obtained " + str(updated_grade) + " in the exam.")
Student 1: John obtained 93.45 in the exam.
Student 2: Anna obtained 53.55 in the exam.
Student 3: Emma obtained 73.5 in the exam.
Popescu (JCU): Lecture 4