Master Exercises
Master Exercises
Objectives
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:
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:
Example:
Testing Functions
Example:
# 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"
The unittest module provides a framework for creating and running tests.
Example:
import unittest
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
You can insert print statements to check variable values at different stages.
Example:
result = divide(10, 2)
print("Result:", result)
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
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
1. Launch PyCharm and open your existing project or create a new one.
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)
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.
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.
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.
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.
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.
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:
A list is a collection of items that are ordered and changeable. You can create a list using square brackets.
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.
Lists are mutable, which means you can change their elements by assigning new values.
To add new elements, use append() to add to the end of the list or insert() to add at a specific position.
You can remove elements using remove(), pop(), or the del keyword.
You can use a for loop to iterate over the elements of a list.
In Python, everything is an object, and objects belong to classes. You can define your own class using
the class keyword.
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.
# Modifying an attribute
book1.pages = 350
print("Updated book info:", book1.get_info())
You can create multiple instances of a class, each with its own attributes.
You can store objects in a list and use a loop to access their methods.
This is optional content for students to practice using lists, objects, and list comprehensions in Python.
# 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}"
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.
A for loop in Python allows you to iterate over all elements of a list easily.
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.
A while loop continues until a condition becomes false. You can use it to iterate over a list based on a condition.
if not found:
print(f"{target} not found in the list")
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.
You can use a for loop to count how many times a certain element appears in a list.
You can sum all the numbers in a list using a for loop.
List comprehensions offer a concise way to create lists. You can also use them to apply transformations to list
elements.
# Solution to Exercise 1
numbers = list(range(1, 21))
total = 0
# Solution to Exercise 2
numbers = [15, 22, 3, 45, 67, 12, 4]
min_num = numbers[0]
# Solution to Exercise 3
numbers = list(range(1, 31))
even_numbers = []