0% found this document useful (0 votes)
28 views16 pages

Master Exercises

Uploaded by

nhatduc317
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
28 views16 pages

Master Exercises

Uploaded by

nhatduc317
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 16

Lab 04: Strings, Testing, and Debugging

Objectives

• Understand string manipulation in Python.


• Learn how to test functions and code segments.
• Explore debugging techniques to identify and fix errors in code.

Table of Contents

1. Introduction to Strings
2. String Manipulation Techniques
3. Testing Functions
4. Debugging Techniques
5. Practice Exercises
6. Using Breakpoints in PyCharm

Introduction to Strings

Strings are sequences of characters enclosed in quotes. They are used to represent text in Python.

Example:

# Creating strings
string1 = "Hello, World!"
string2 = 'Python is fun!'
print(string1)
print(string2)

String Characteristics:

• Strings are immutable: Once created, they cannot be changed.


• Strings can be indexed and sliced.

String Manipulation Techniques

Python provides various methods to manipulate strings:

1. Accessing Characters:

my_string = "Hello"
print(my_string[0]) # H
print(my_string[-1]) # o
2. Slicing Strings:

print(my_string[1:4]) # ell
print(my_string[:3]) # Hel
print(my_string[2:]) # llo

3. String Methods:

• len(): Returns the length of the string.


• .lower(): Converts string to lowercase.
• .upper(): Converts string to uppercase.
• .replace(old, new): Replaces substrings.
• .split(separator): Splits string into a list.
• .join(iterable): Joins elements of an iterable into a string.

Example:

sample_string = "Python Programming"


print("Length:", len(sample_string)) # 18
print("Lowercase:", sample_string.lower()) # python programming
print("Uppercase:", sample_string.upper()) # PYTHON PROGRAMMING
print("Replaced:", sample_string.replace("Programming", "Language")) # Python Language
print("Split:", sample_string.split(" ")) # ['Python', 'Programming']

Testing Functions

Testing is an essential part of programming to ensure code works as expected.

1. Writing Test Cases

You can use assertions to test the expected outcomes of functions.

Example:

def add(a, b):


return a + b

# Test cases
assert add(2, 3) == 5, "Test Case 1 Failed"
assert add(-1, 1) == 0, "Test Case 2 Failed"
assert add(0, 0) == 0, "Test Case 3 Failed"

print("All test cases pass")

2. Using unittest Framework

The unittest module provides a framework for creating and running tests.

Example:
import unittest

def multiply(a, b):


return a * b

class TestMathFunctions(unittest.TestCase):
def test_multiply(self):
self.assertEqual(multiply(3, 4), 12)
self.assertEqual(multiply(-1, 1), -1)

if __name__ == '__main__':
unittest.main()

Debugging Techniques

Debugging is the process of identifying and fixing errors in your code.

1. Using Print Statements

You can insert print statements to check variable values at different stages.

Example:

def divide(a, b):


print(f"Dividing {a} by {b}")
return a / b

result = divide(10, 2)
print("Result:", result)

2. Using Python Debugger (pdb)

Python includes a built-in debugger that allows you to set breakpoints, step through code, and inspect variable states.

Example:

import pdb

def calculate_area(radius):
pdb.set_trace() # Set a breakpoint
return 3.14 * radius ** 2

area = calculate_area(5)
print("Area:", area)

Practice Exercises

1. String Manipulation Exercise:


o Write a function that takes a string as input and returns the string reversed.
2. def reverse_string(s):
3. return s[::-1]
4.
print(reverse_string("Hello")) # Output: olleH

5. Testing Exercise:
o Write a function that checks if a string is a palindrome and create test cases to verify it.
6. def is_palindrome(s):
7. return s == s[::-1]
8.
9. # Test cases
10. assert is_palindrome("radar") == True
assert is_palindrome("hello") == False

11. Debugging Exercise:


o Create a function that calculates the factorial of a number. Intentionally introduce an error, then use
print statements or pdb to debug it.
12. def factorial(n):
13. if n == 0:
14. return 1
15. return n * factorial(n - 1)
16.
print(factorial(5)) # Output: 120

Using Breakpoints in PyCharm

Step 1: Open Your Project

1. Launch PyCharm and open your existing project or create a new one.

Step 2: Write or Open Your Code

1. Write your Python code or open the existing file you want to debug.

Example:

def factorial(n):
if n == 0:
return 1
return n * factorial(n - 1)

print(factorial(5)) # This will calculate 5! (120)

Step 3: Set a Breakpoint

1. Set a Breakpoint: Click in the gutter (the left margin) next to the line number where you want the program to
pause execution. A red dot will appear, indicating a breakpoint has been set.
2. You can set multiple breakpoints if needed.
Step 4: Start the Debugger

1. Run in Debug Mode: Right-click on your Python file in the Project tool window or the editor and
select Debug 'your_script_name'. Alternatively, you can click on the green bug icon in the top right corner of
the PyCharm window.

Step 5: Debugging Interface

1. Once the debugger starts, the program will run until it hits the first breakpoint.
2. When execution pauses, the Debug tool window will appear at the bottom of the PyCharm interface. This
window provides various options and information:
o Variables: Shows the current variable values.
o Frames: Displays the call stack, allowing you to navigate through the function calls.
o Watches: You can add expressions to monitor their values as you step through the code.

Step 6: Step Through the Code

1. Step Over (F8): Execute the current line and move to the next line in the same function. Use this when you
want to skip over function calls without entering them.
2. Step Into (F7): If the current line contains a function call, this will take you into that function to debug it line
by line.
3. Step Out (Shift + F8): Finish the current function and return to the calling function.
4. Resume Program (F9): Continue running the code until the next breakpoint or until the program finishes.

Step 7: Inspect Variables

1. Hover Over Variables: While execution is paused, you can hover over variables in your code to see their
current values.
2. Watch Variables: In the Watches panel, you can add expressions or variable names to monitor their values
continuously.

Step 8: Modify Variables

1. While the execution is paused, you can change the value of variables in the Variables panel. This can help you
test different scenarios without restarting the program.

Step 9: Remove Breakpoints

1. To remove a breakpoint, click on the red dot in the gutter again, or right-click the line and select Remove
Breakpoint.
2. You can also disable breakpoints without removing them by clicking on the Breakpoints icon in the Debugger
panel and unchecking the specific breakpoint.

Additional Tips

• Conditional Breakpoints: Right-click on a breakpoint and choose Edit Breakpoint to add conditions. The
program will only pause if the condition evaluates to True.
• Log Message Breakpoints: You can configure a breakpoint to log a message to the console instead of pausing
execution.
• if Statement in Python
• If the simple code of block is to be performed if the condition holds true then the if statement is used. Here the
condition mentioned holds then the code of the block runs otherwise not.
• # Syntax
• if condition:
• # Statements to execute if condition is true

• Basic Conditional Check with if Statement
• In this example, an if statement checks if 10 is greater than 5. If true, it prints "10 greater than 5"; regardless, it
then prints "Program ended" as the next statement, indicating the program flow.
• # if statement example
• if 10 > 5:
• print("10 greater than 5")

• print("Program ended")
• 10 greater than 5
• Program ended

• if-else Statement in Python
• In conditional if Statement the additional block of code is merged as else statement which is performed when
if condition is false.
• # Syntax:
• if (condition):
• # Executes this block if condition is true
• else:
• # Executes this block if condition is false

• Example: Handling Conditional Scenarios with if-else
• In this example, the code assigns the value 3 to variable x and uses an if-else statement to check if x is equal to
4. If true, it prints "Yes"; otherwise, it prints "No", demonstrating a conditional branching structure.
• # if-else statement example
• x=3
• if x == 4:
• print("Yes")
• else:
• print("No")
• No

• Example: Nested if-else Chain for Multiple Conditions
• # if-else chain statement
• letter = "A"

• if letter == "B":
• print("letter is B")
• else:
• if letter == "C":
• print("letter is C")
• else:
• if letter == "A":
• print("letter is A")
• else:
• print("letter isn't A, B and C")
• letter is A

• Nested if Statement
• if statement can also be checked inside other if statement. This conditional statement is called a nested if
statement. This means that inner if condition will be checked only if outer if condition is true and by this, we
can see multiple conditions to be satisfied.
• # Syntax
• if (condition1):
• # Executes when condition1 is true
• if (condition2):
• # Executes when condition2 is true
• # if Block is end here
• # if Block is end here

• Example: Managing Nested Conditions for Refined Control
• # Nested if statement example
• num = 10

• if num > 5:
• print("Bigger than 5")

• if num <= 15:
• print("Between 5 and 15")
• Bigger than 5
• Between 5 and 15

• if-elif Statement in Python
• The if-elif statement is shortcut of if-else chain. While using if-elif statement at the end else block is added
which is performed if none of the above if-elif statement is true.
• # Syntax:
• if (condition):
• # statement
• elif (condition):
• # statement
• else:
• # statement

• Example: Sequential Evaluation with if-elif-else Structure
• # if-elif statement example
• letter = "A"

• if letter == "B":
• print("letter is B")

• elif letter == "C":
• print("letter is C")

• elif letter == "A":
• print("letter is A")

• else:
• print("letter isn't A, B or C")
• letter is A
Lab 06: Lists and Objects

Objectives:

• Understand how to create and manipulate lists in Python.


• Practice using list methods and accessing elements.
• Introduction to objects and methods in Python.

Section 1: Working with Lists

1.1 Creating a List

A list is a collection of items that are ordered and changeable. You can create a list using square brackets.

# Creating a list of fruits


fruits = ["apple", "banana", "cherry", "date", "elderberry"]
print("List of fruits:", fruits)

1.2 Accessing List Elements

Lists are zero-indexed, meaning the first element is at index 0. You can also use negative indices to access elements
from the end of the list.

# Access the first and the last element of the list


print("First fruit:", fruits[0])
print("Last fruit:", fruits[-1])

1.3 Modifying List Elements

Lists are mutable, which means you can change their elements by assigning new values.

# Changing the second fruit to blueberry


fruits[1] = "blueberry"
print("Updated list of fruits:", fruits)
1.4 List Slicing

You can use slicing to access a range of elements in the list.

# Slicing the list to get a subset of elements


print("First three fruits:", fruits[:3]) # From index 0 to 2
print("Fruits from index 2 to 4:", fruits[2:4]) # From index 2 to 3

1.5 Adding Elements to a List

To add new elements, use append() to add to the end of the list or insert() to add at a specific position.

# Adding an element at the end of the list


fruits.append("fig")
print("List after appending fig:", fruits)

# Inserting an element at a specific index


fruits.insert(2, "grape")
print("List after inserting grape at index 2:", fruits)

1.6 Removing Elements from a List

You can remove elements using remove(), pop(), or the del keyword.

# Removing an element by value


fruits.remove("date")
print("List after removing date:", fruits)

# Removing an element by index and returning it


removed_fruit = fruits.pop(1)
print("Removed fruit:", removed_fruit)
print("List after pop:", fruits)

1.7 List Length

The len() function returns the number of elements in a list.

# Getting the length of the list


print("Length of the list:", len(fruits))

1.8 Iterating Over a List

You can use a for loop to iterate over the elements of a list.

# Iterating over the list and printing each fruit


print("Fruits in the list:")
for fruit in fruits:
print(fruit)
Section 2: Objects in Python

2.1 Introduction to Objects and Classes

In Python, everything is an object, and objects belong to classes. You can define your own class using
the class keyword.

# Defining a simple class to represent a Book object


class Book:
def __init__(self, title, author, pages):
self.title = title
self.author = author
self.pages = pages

# A method to get information about the book


def get_info(self):
return f"{self.title} by {self.author}, {self.pages} pages"

# Creating an instance of the Book class


book1 = Book("1984", "George Orwell", 328)
print("Book info:", book1.get_info())
Students will learn about classes and objects in Python, including how to define a class, create instances of a class, and
access attributes and methods of objects in a later lesson. This section provides a brief introduction to the concept of
objects and classes in Python.

2.2 Attributes and Methods

Attributes are variables that belong to an object, while methods are functions that belong to an object. You can access
attributes directly or use methods to manipulate them.

# Accessing attributes directly


print("Book title:", book1.title)
print("Book author:", book1.author)
print("Book pages:", book1.pages)

# Modifying an attribute
book1.pages = 350
print("Updated book info:", book1.get_info())

2.3 Creating Multiple Instances

You can create multiple instances of a class, each with its own attributes.

# Creating multiple instances of the Book class


book2 = Book("To Kill a Mockingbird", "Harper Lee", 281)
book3 = Book("The Great Gatsby", "F. Scott Fitzgerald", 180)

print("Book 2 info:", book2.get_info())


print("Book 3 info:", book3.get_info())

Section 3: List of Objects

3.1 Creating a List of Objects

You can store objects in a list and use a loop to access their methods.

# Storing Book objects in a list


library = [book1, book2, book3]

# Iterating over the list of books and printing their information


print("Books in the library:")
for book in library:
print(book.get_info())

Section 4: List Comprehensions

4.1 Simple List Comprehension

List comprehensions allow you to create lists in a concise way.

# Creating a list of squared numbers using list comprehension


numbers = [1, 2, 3, 4, 5]
squared_numbers = [x**2 for x in numbers]
print("Squared numbers:", squared_numbers)

4.2 Filtering with List Comprehension

You can also add conditions to a list comprehension.

# Creating a list of even numbers using list comprehension


even_numbers = [x for x in numbers if x % 2 == 0]
print("Even numbers:", even_numbers)

Section 5: Lab Exercises

This is optional content for students to practice using lists, objects, and list comprehensions in Python.

Exercise 1: List Operations

1. Create a list of integers from 1 to 10.


2. Print the square of each number.
3. Remove all odd numbers from the list.
4. Add 11 to the list.
# Solution to Exercise 1
integers = list(range(1, 11))
print("List of integers:", integers)

# Squaring each integer


squares = [x**2 for x in integers]
print("Squares of integers:", squares)

# Removing odd numbers


integers = [x for x in integers if x % 2 == 0]
print("Even integers:", integers)

# Adding 11 to the list


integers.append(11)
print("List after adding 11:", integers)

Exercise 2: Creating and Using a Class

1. Create a Car class with attributes brand, model, and year.


2. Add a method car_info() to return the car's details.
3. Create three instances of the class, store them in a list, and print each car's details.

# Solution to Exercise 2
class Car:
def __init__(self, brand, model, year):
self.brand = brand
self.model = model
self.year = year

def car_info(self):
return f"{self.brand} {self.model}, {self.year}"

# Creating instances of the Car class


car1 = Car("Toyota", "Camry", 2020)
car2 = Car("Honda", "Accord", 2018)
car3 = Car("Tesla", "Model 3", 2021)

# Storing cars in a list


garage = [car1, car2, car3]

# Printing car details


print("Cars in the garage:")
for car in garage:
print(car.car_info())
Lab 07: Lists, Iteration, and Loops

Objectives:
• Understand how to use loops (for and while) to iterate through lists.
• Practice different ways of iterating over lists in Python.
• Learn how to apply loops for various operations on lists, such as searching, counting, and modifying list
elements.

Section 1: Lists and for Loops

1.1 Introduction to for Loops with Lists

A for loop in Python allows you to iterate over all elements of a list easily.

# A simple for loop that prints each element in a list


numbers = [1, 2, 3, 4, 5]
for num in numbers:
print(num)
Here, the for loop goes through each element of the numbers list and prints it.

1.2 Using range() with for Loops

You can also use the range() function to loop through a sequence of numbers, which can be useful when you want to
use the index of a list.

# Using range() to loop through indices of the list


for i in range(len(numbers)):
print(f"Index {i}: {numbers[i]}")
The range(len(numbers)) gives us a sequence of indices, and we can use it to access list elements.

1.3 Modifying a List with for Loops

We can use a for loop to modify elements in a list.

# Doubling each number in the list


for i in range(len(numbers)):
numbers[i] = numbers[i] * 2
print("List after doubling:", numbers)
Note: Be cautious when modifying a list while iterating through it.

Section 2: Lists and while Loops

2.1 Introduction to while Loops with Lists

A while loop continues until a condition becomes false. You can use it to iterate over a list based on a condition.

# Using a while loop to print all elements in the list


index = 0
while index < len(numbers):
print(numbers[index])
index += 1 # Move to the next element
Here, the while loop goes through each element of the list based on the index.

2.2 while Loop for Searching in a List

A common use of a while loop is to search for a specific element in a list.

# Searching for a number in the list using a while loop


target = 8
index = 0
found = False

while index < len(numbers) and not found:


if numbers[index] == target:
found = True
print(f"Found {target} at index {index}")
index += 1

if not found:
print(f"{target} not found in the list")

Section 3: Nested Loops with Lists

3.1 Nested for Loops

A nested loop is when a loop runs inside another loop. You can use this to work with 2D lists or perform operations
involving multiple lists.

# Example of a nested loop: Multiplication table


for i in range(1, 4): # Outer loop
for j in range(1, 4): # Inner loop
print(f"{i} x {j} = {i * j}")
print() # Blank line after each row
Nested loops allow you to combine elements or perform operations like matrix multiplication.

Section 4: Practical Examples of List Operations with Loops

4.1 Counting Elements in a List

You can use a for loop to count how many times a certain element appears in a list.

# Counting the occurrences of the number 8 in the list


numbers = [2, 4, 8, 8, 10, 12, 8]
count = 0

for num in numbers:


if num == 8:
count += 1

print(f"Number 8 appears {count} times in the list")

4.2 Finding the Maximum Value in a List

Use a for loop to find the maximum value in a list.

# Finding the maximum value in a list


numbers = [2, 4, 8, 10, 12, 3]
max_num = numbers[0]

for num in numbers:


if num > max_num:
max_num = num

print(f"The maximum value in the list is: {max_num}")

4.3 Summing the Elements of a List

You can sum all the numbers in a list using a for loop.

# Summing all numbers in the list


total = 0

for num in numbers:


total += num

print(f"The sum of the numbers in the list is: {total}")

4.4 Using List Comprehensions

List comprehensions offer a concise way to create lists. You can also use them to apply transformations to list
elements.

# Doubling all numbers in a list using list comprehension


doubled_numbers = [num * 2 for num in numbers]
print("Doubled numbers:", doubled_numbers)

Section 5: Lab Exercises

Exercise 1: Sum and Average of List Elements

1. Create a list of integers from 1 to 20.


2. Write a loop to calculate the sum of all elements in the list.
3. Calculate and print the average of the list.

# Solution to Exercise 1
numbers = list(range(1, 21))
total = 0

# Calculating the sum


for num in numbers:
total += num

average = total / len(numbers)


print(f"Sum: {total}, Average: {average}")

Exercise 2: Find the Minimum Value in a List

1. Create a list of random integers.


2. Write a loop to find the minimum value in the list.

# Solution to Exercise 2
numbers = [15, 22, 3, 45, 67, 12, 4]
min_num = numbers[0]

# Finding the minimum value


for num in numbers:
if num < min_num:
min_num = num

print(f"The minimum value in the list is: {min_num}")

Exercise 3: Filter Even Numbers Using a Loop

1. Create a list of numbers from 1 to 30.


2. Write a loop that adds only the even numbers to a new list.
3. Print the new list of even numbers.

# Solution to Exercise 3
numbers = list(range(1, 31))
even_numbers = []

# Filtering even numbers


for num in numbers:
if num % 2 == 0:
even_numbers.append(num)

print("Even numbers:", even_numbers)

Exercise 4: Multiplication Table Using Nested Loops

You might also like