L4: Conditional Statements, Loops, and Lists

Bogdan G. Popescu

John Cabot University

Comparison Operators

Introduction

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 to

Comparison Operators

Examples of Comparison Operators

Equal to and Not Equal to

# Using Equal to
a = 5
b = 10
print(a == b) 
False
# Using Not Equal to
print(a != b) 
True

Greater Than and Less Than

# Greater Than
print(a > b)
False
# Less Than
print(a < b)
True

Conditional Statements

Introduction

  • Conditional statements allow us to execute specific code based on certain conditions.
  • They are fundamental in controlling the flow of a program.
  • Common types of conditional statements in Python:
    • if
    • elif
    • else

Conditional Statements

Syntax of Conditional Statements

This is what the syntax of conditional statements looks like:

if condition:
    # code to execute if condition is True
elif another_condition:
    # code to execute if another_condition is True
else:
    # code to execute if all conditions are False

Example: Simple If Statement

age = 18

if age >= 18:
    print("You are eligible to vote.")
You are eligible to vote.

Conditional Statements

Syntax of Conditional Statements

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.

temperature = 30

if temperature > 25:
    print("It's a hot day!")
else:
    print("It's a pleasant day!")
It's a hot day!

Conditional Statements

Syntax of Conditional Statements

Example: If-Elif-Else Statement

The following code evaluates the score and prints the corresponding grade based on the defined ranges.

score = 85

if score >= 90:
    print("Grade: A")
elif score >= 80:
    print("Grade: B")
elif score >= 70:
    print("Grade: C")
else:
    print("Grade: D")
Grade: B

Conditional Statements

elif statements

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

Example:

if condition1:
    # This block will execute if condition1 is true
elif condition2:
    # This block will execute if condition1 is false and condition2 is true
elif condition3:
    # This block will execute if condition1 and condition2 are false and condition3 is true

Other Operations

Difference if and elif

Other Operations

Difference if and elif

Use if:

  • when you want to check multiple conditions independently of each other
  • when multiple conditions can be true at the same time and you want to execute the corresponding blocks for all true conditions.
if condition1:
    # This block will execute if condition1 is true
if condition2:
    # This block will execute if condition2 is true (independently of condition1)

Other Operations

Difference if and elif

Use elif:

  • when you want to check multiple conditions dependent on each other
  • when only one block should be executed among multiple conditions
  • the elif block will be checked only if the preceding if and elif conditions were false
if condition1:
    # This block will execute if condition1 is true
elif condition2:
    # This block will execute if condition1 is false and condition2 is true
elif condition3:
    # This block will execute if condition1 and condition2 are false and condition3 is true

Other Operations

Example use if vs. elif

  • Using if (independent conditions)
weather = "rainy"
if weather == "rainy":
    print("Take an umbrella.")
if weather == "windy":
    print("Wear a windbreaker.")
if weather == "sunny":
    print("Wear sunglasses.")
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.

Other Operations

Example use if vs. elif

  • Using elif (dependent conditions)
weather = "rainy"
if weather == "rainy":
    print("Take an umbrella.")
elif weather == "windy":
    print("Wear a windbreaker.")
elif weather == "sunny":
    print("Wear sunglasses.")
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.

Other Operations

Example use if vs. elif

  • Using elif (dependent conditions)

  • Here is when elif gets executed

weather = "windy"
if weather == "rainy":
    print("Take an umbrella.")
elif weather == "windy":
    print("Wear a windbreaker.")
elif weather == "sunny":
    print("Wear sunglasses.")
Wear a windbreaker.
  • Once again, the elif block will be checked only if the preceding if and elif conditions were false

Other Operations

The else statement

The 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.

weather = "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.")

Other Operations

The else statement

weather = "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.

Other Operations

The else statement

weather = "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 else statement catches any other weather conditions not covered by the if and elif statements and prints “Check weather & dress well”.

Other Operations

Exercise:

Write a program using if, elif, and else that prints a letter grade for students.

Here are the rules:

  • If the score is 90 or above, the grade is ‘A’
  • If the score is 80 or above but less than 90, the grade is ‘B’
  • If the score is 70 or above but less than 80, the grade is ‘C’
  • If the score is 60 or above but less than 70, the grade is ‘D’
  • If the score is less than 60, the grade is ‘F’

Let’s start with grade=92

Other Operations

Exercise:

This is how we can wite this:

grade = 92

if grade >= 90:
  print("A")
elif grade >= 80:
  print("B")
elif grade >= 70:
  print("C")
elif grade >= 60:
  print("D")
else:
  print("F")
A

Other Operations

Exercise:

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.

Other Operations

Exercise:

What if the grade was 72?

Other Operations

Exercise:

What if the grade was 72?

grade = 72

if grade >= 90:
  print("A")
elif grade >= 80:
  print("B")
elif grade >= 70:
  print("C")
elif grade >= 60:
  print("D")
else:
  print("F")
C

Error Handling in Python: try and except

What is Error Handling?

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?

  • Use try to test a block of code for errors.
  • Use except to handle the error if one occurs.

Error Handling in Python: try and except

Basic Syntax

This the basic syntax:

try:
    # Code that might raise an error
except:
    # Code to execute if an error occurs

Example:

try:
    number = 10
    print(100 / number)
except ValueError:
    print("You must enter a valid number!")
except ZeroDivisionError:
    print("Cannot divide by zero!")
10.0

Error Handling in Python: try and except

Key Points

  • try: The block where you attempt to execute code that might fail.
  • except: The block that handles the error if the code in try fails.

You can have multiple except blocks to handle different types of errors.

Lists

Introduction

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:

students = ["Alice", "Tom", "Eugene"]
print(students)
['Alice', 'Tom', 'Eugene']

The following is also a list:

descriptions = ['Alice a sophomore', 'Tom is also a sophomore', 'Eugene is a freshman']
print(descriptions)
['Alice a sophomore', 'Tom is also a sophomore', 'Eugene is a freshman']

Lists

Accessing one item in a list

We can access items in a list in the following way:

descriptions = ['Alice a sophomore', 'Tom is also a sophomore', 'Eugene is a freshman']
print(descriptions[0])
Alice a sophomore

We can access the second item in the following way:

descriptions = ['Alice a sophomore', 'Tom is also a sophomore', 'Eugene is a freshman']
print(descriptions[1])
Tom is also a sophomore

Thus, notice that item enumeration starts from 0.

Lists

Accessing one item in a list

We can get the last item of a list in the following way

descriptions = ['Alice a sophomore', 'Tom is also a sophomore', 'Eugene is a freshman']
print(descriptions[-1])
Eugene is a freshman

We can get the second the last item from a list

descriptions = ['Alice a sophomore', 'Tom is also a sophomore', 'Eugene is a freshman']
print(descriptions[-2])
Tom is also a sophomore

Lists

Exercise 1

Store the values ‘python’, ‘c’, and ‘java’ in a list. Print each of these values out, using their position in the list.

Lists

Exercise 1

Store the values ‘python’, ‘c’, and ‘java’ in a list. Print each of these values out, using their position in the list.

list_lan = ["python", "c", "java"]
list_lan[0]
'python'
list_lan[1]
'c'
list_lan[2]
'java'

Lists

Exercise 2

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.’

Lists

Exercise 2

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.’

list_students = ["John", "Anna", "Emma"]
print(list_students[0] + " is one of the students taking the class.")
John is one of the students taking the class.
print(list_students[1] + " is one of the students taking the class.")
Anna is one of the students taking the class.
print(list_students[2] + " is one of the students taking the class.")
Emma is one of the students taking the class.

Loops

Introduction

A loop is used to execute a given code section more than once.

A for loop is composed of:

  • The for keyword
  • The in keyword
  • The vector we go over (sequence)
  • A code which defines what to do with each element (expression)

Loops

Syntax

This is the syntax in a for loop

for symbol in sequence:
  expression

This is an example with numbers:

list_numbers = [1,2,3]
for number in list_numbers:
  print(number)
1
2
3

Loops

Loop Example

Here is another example with strings:

list_students = ["John", "Anna", "Emma"]
for student in list_students:
  print(student)
John
Anna
Emma

Loops

Exercises with Loops 1

  1. Create a vector of numbers from 1 to 10.
  2. Use a for loop to iterate through the vector and print each element.
  3. Calculate the square of each element and store it in a new vector.
  4. Print the original vector and the vector containing the squares.

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

Loops

Exercises with Loops 2

  1. Create a vector of numbers from 1 to 15.
  2. Use a for loop to iterate through the vector and print each element.
  3. Calculate the square root of each element and store it in a new vector.
  4. Print the original vector and the vector containing the square root.

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

Loops

Exercises with Loops 3

  1. Use the following list list_students = ["John", "Anna", "Emma"]
  2. Use a 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.

Loops

Exercises with Loops 3

  1. Use the following list list_students = ["John", "Anna", "Emma"]
  2. Use a 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.

Loops

Breaks

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.

list_students = ["John", "Anna", "Emma"]
for student in list_students:
  if student == "Anna":
    break
  print(student + " is one of the students taking the class.")
John is one of the students taking the class.

Loops

Breaks

The use of break is even more apparent in the following case:

for i in range(1, 100):
    if i % 3 == 0 and i % 7 == 0:
        print(i, "divisible by 3 and 7")
        break
21 divisible by 3 and 7

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.

Loops

Enumerating a list

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

Loops

Enumerating a 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.

List Operations

The zip() function

The 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.

List Operations

The zip() function

Here is an example:

list_students = ["John", "Anna", "Emma"]
list_grades = [89, 51, 70]
for student, grade in zip(list_students, list_grades):
  print(student + " obtained " + str(grade) + " in the exam.")
John obtained 89 in the exam.
Anna obtained 51 in the exam.
Emma obtained 70 in the exam.

List Operations

The zip() function

We 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.

List Operations

The zip() function Exercise

Suppose 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 Operations

The zip() function Exercise solution

Suppose 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.