L4: Loops, Lists, Breaks, and Zip Functions

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

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

Comparison Operators

Examples of Comparison Operators

Greater Than and Less Than

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

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 is the basic syntax:

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

Example:

Python
try:
    number = 10
    print(100 / number)
except Exception as e:
  print(f"An error occurred: {e}")
10.0

Error Handling in Python: try and except

Basic Syntax

This is the basic syntax:

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

Another Example:

Python
try:
    number = 0
    print(100 / number)
except Exception as e:
  print(f"An error occurred: {e}")
An error occurred: division by zero

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 collections of items that are stored in a variable

The following is a list:

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

The following is also a list:

Python
descriptions = ['Alice is a sophomore', 'Tom is also a sophomore', 'Eugene is a freshman']
print(descriptions)
['Alice is 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:

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

We can access the second item in the following way:

Python
descriptions = ['Alice is 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 on a list in the following way:

Python
descriptions = ['Alice is 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

Python
descriptions = ['Alice is 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 value using its position in the list.

Lists

Exercise 1

Store the values ‘python’, ‘c’, and ‘java’ in a list. Print each value using its position in the list.

Python
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. Using their position in the list, print a statement about each value.

Your statement could simply be, ‘“Value” is one of the students taking the class.’

Lists

Exercise 2

Store the values ‘John’, ‘Anna’, and ‘Emma’ in a list. Using their position in the list, print a statement about each value.

Your statement could simply be, ‘“Value” is one of the students taking the class.’

Loops

Introduction

A loop executes 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 that defines what to do with each element (expression)

Loops

Syntax

This is the syntax in a for loop.

Python
for item in sequence:
  expression about item

This is an example with numbers:

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

Loops

Loop Example

Here is another example with strings:

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

Loops

Exercises with Loops 1

  1. Create a vector of numbers from 1 to 5
  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 the following:

1 1
2 4
3 9
4 16
5 25

Loops

Exercises with Loops 2

  1. Create a vector of numbers from 1 to 5
  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 the following:

1 1.0
2 1.4142135623730951
3 1.7320508075688772
4 2.0
5 2.23606797749979

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.

Python
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:

Python
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 a number that could be divided by 3 and 7.

Rather than going through the whole range from 1 to 100, the loop stops when it encounters a number divisible by both 3 and 7.

Loops

Enumerating a list

When looping through a list, identifying the index of a current item may often be necessary.

The enumerate() function takes the index, and then it loops through the list.

For example:

Python
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:

Python
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:

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

Python
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 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 you want to increase the grade for John, Anna, and Emma by 5%.

Use the previous code to update the grades by 5%.

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

Conclusion

Comparison operators and conditional statements enable decision-making in programs.

Lists store multiple items, and loops process them efficiently.

try and excepthandle errors gracefully for robust code.

Tools like break, enumerate, and zip enhance loop functionality.