Python Manual (2)
Python Manual (2)
PYTHON
Course Manual
Prepared By:
Dr. Muhammad Asif Khan
Assistant Professor
Sukkur IBA University
Table of Contents
Python Programming Bootcamp – Recommended Resources ........................................... 4
Incremental Development of Project an Overview ............................................................. 7
Week 1: Introduction to Programming and Python Basics ................................................ 9
Day 1: Introduction to Programming Concepts .............................................................. 9
Day 2: Variables and Arithmetic Operations ................................................................ 12
Day 3: Input and Output ............................................................................................... 16
Day 4: Control Flow - If Statements .............................................................................. 20
Day 5: Project Day ......................................................................................................... 26
Week 2: Control Flow and Looping ................................................................................... 29
Day 1: Loops – Introduction to While Loop .................................................................. 29
Day 2: Loops – Introduction to For Loop ...................................................................... 33
Day 3: Combining Control Flow and Loops ................................................................... 37
Day 4: Lists – Introduction and Basic Operations ......................................................... 42
Day 5: Project Day ......................................................................................................... 46
Week 3: Functions and More Data Structures ................................................................. 50
Day 1: Introduction to Functions .................................................................................. 50
Day 2: Lists – Advanced Operations.............................................................................. 54
Day 3: Tuples and Dictionaries...................................................................................... 58
Day 4: Error Handling and Debugging........................................................................... 62
Day 5: Project Day ......................................................................................................... 67
Week 4: File Handling and Basic Project Structuring ........................................................ 70
Day 1: Introduction to File Handling ............................................................................. 70
Day 2: Working with Files (Continued) ......................................................................... 74
Day 3: Structuring a Python Project .............................................................................. 79
Day 4: Project Day Preparation..................................................................................... 85
Day 5: Project Day ......................................................................................................... 89
Week 5: Introduction to Object-Oriented Programming (OOP)....................................... 94
Day 1: Introduction to Classes and Objects .................................................................. 94
Day 2: More on Classes and Methods .......................................................................... 99
Day 3: Inheritance and Polymorphism ....................................................................... 106
Day 4: Working with Objects in the Project ................................................................ 112
Day 5: Project Day ....................................................................................................... 120
2
Week 6: Introduction to APIs and External Libraries ...................................................... 126
Day 1: Introduction to APIs ......................................................................................... 126
Day 2: External Libraries and Packages....................................................................... 130
Day 3: Integrating APIs into the Project...................................................................... 133
Day 4: Project Enhancement with Libraries................................................................ 138
Day 5: Project Day ....................................................................................................... 142
Week 7: Advanced Python Concepts and Data Visualization ......................................... 146
Day 1: Advanced Functions and Recursion ................................................................. 146
Day 2: Introduction to Data Visualization ................................................................... 150
Day 3: Data Manipulation with Pandas ...................................................................... 159
Day 4: Enhancing the To-Do List with Data Visualization ........................................... 166
Day 5: Project Day ....................................................................................................... 173
Week 8: Project Finalization and Deployment ............................................................... 176
Day 1: Review of All Key Concepts .............................................................................. 176
Day 2: Final Project Adjustments ................................................................................ 186
Day 3: Introduction to Git and Version Control .......................................................... 192
Day 4: Project Deployment ......................................................................................... 197
Day 5: Final Project Presentation................................................................................ 201
3
Python Programming Bootcamp – Recommended Resources
Books
Online Tutorials
1. Real Python
o URL: realpython.com
o Description: Real Python provides high-quality tutorials and courses
on a wide range of Python topics, from beginner to advanced levels. It
includes step-by-step guides and coding examples.
4
2. W3Schools – Python Tutorial
o URL: w3schools.com/python
o Description: A great beginner-friendly resource that offers interactive
tutorials on basic Python concepts, control flow, data structures, and
more.
3. Learn Python – Python.org
o URL: docs.python.org/3/tutorial
o Description: The official Python documentation provides a thorough
tutorial covering everything from Python syntax to advanced concepts
such as object-oriented programming.
4. Code Academy – Learn Python
o URL: codecademy.com/learn/learn-python-3
o Description: A beginner-friendly, interactive course designed to teach
Python from the ground up. It includes hands-on exercises, quizzes,
and projects.
5. SoloLearn – Python for Beginners
o URL: sololearn.com
o Description: SoloLearn offers bite-sized lessons on Python, making it
perfect for learners who want to practice Python on the go.
6. GeeksforGeeks Python Programming Language
o URL: geeksforgeeks.org/python-programming-language/
o Description: A comprehensive set of Python tutorials that covers a
wide range of topics, including control structures, object-oriented
programming, and data structures.
Online Compilers
1. Replit
o URL: replit.com
o Description: An excellent cloud-based IDE that supports Python and
many other programming languages. Replit allows you to write, run,
and debug code directly in the browser.
2. PythonAnywhere
o URL: pythonanywhere.com
o Description: A browser-based Python development and hosting
environment that allows you to run Python scripts without the need
for local installations.
3. Programiz – Python Compiler
o URL: programiz.com/python-programming/online-compiler/
o Description: A simple, online Python compiler that lets you write and
execute Python code instantly. Great for quick testing and debugging.
4. JDoodle
o URL: jdoodle.com/python3-programming-online/
5
o Description: A versatile online compiler that supports Python 3 and
includes features such as code sharing and API integration.
5. Pycharm Edu
o URL: jetbrains.com/pycharm-edu/
o Description: A free educational IDE by JetBrains designed for learning
and teaching Python. It provides an interactive coding environment
with in-built exercises and quizzes.
Note: Each of the resources listed here is intended to supplement your learning
throughout the Python Bootcamp. Feel free to explore different resources based on
your learning style and objectives. All of the abovemention books’ pdfs can be
downloaded free from the internet.
6
Incremental development of a Project
Welcome to the Python Programming Bootcamp! Throughout this course, you will
work on a Task Management System project, which will be built progressively as
you learn Python programming concepts. This project will help you apply
everything you learn in a practical, hands-on manner, from basic control flow to
more advanced techniques like file handling, object-oriented programming, and
working with external libraries.
1. Objective:
By the end of this course, you will have developed a fully functional Task
Management System that allows users to:
7
● Week 7: Data Visualization and Advanced Features
o Add data visualization to display task completion progress over time
using Python libraries like Matplotlib.
● Week 8: Project Finalization and Deployment
o Review and refine your code, deploy the project, and present the final
version as your capstone project for this course.
Learning Outcomes:
This Task Management System project will serve as a practical application of the concepts
you learn each week, making your learning experience more engaging and rewarding. By
the end of the course, you'll have a complete project to showcase as a part of your
programming portfolio.
8
Lab Manual for Week 1: Basic Task Input
and Output - Day 1
Day 1: Introduction to Python, Installation, and Basic Concepts
Time: 3 Hours
Learning Outcomes:
- Install Python and set up an Integrated Development Environment (IDE).
- Understand basic programming concepts.
- Write and execute your first Python program.
- Work with basic data types (strings, integers).
- Understand how to declare and use variables.
Tasks:
1. Install Python and IDE Setup (45 mins):
- Python Installation: Visit https://www.python.org/downloads/ and download the latest
version of Python.
- Run the installer, and ensure you check the box that says 'Add Python to PATH' during
installation.
- Verify the installation by opening a terminal/command prompt and typing:
`python --version`
- Install an IDE like Visual Studio Code or PyCharm.
- You may also use online compilers, those are mentioned in above resources section.
9
5. Introduction to Variables (30 mins):
- Understand variables and how they store data.
- Assign values to variables and display them using `print()`.
name = 'Alice'
age = 30
favorite_food = 'Pasta'
print('Name:', name)
print('Age:', age)
print('Favorite Food:', favorite_food)
name = 'Alice'
age = 30
height = 5.5
print('Type of name:', type(name))
print('Type of age:', type(age))
print('Type of height:', type(height))
10
name = input('Enter your name: ')
age = int(input('Enter your age: '))
years_left = 100 - age
print('Hello ' + name + '! You will turn 100 in ' + str(years_left)
+ ' years.')
Assignment:
Write a detailed Python program that asks the user for the following details:
- Full name
- Age
- Favorite hobby
- Year of birth
11
Lab Manual for Week 1: Basic Task Input
and Output - Day 2
Day 2: Variables, Arithmetic Operations, and Data Types
Time: 3 Hours
Learning Outcomes:
- Understand how variables work in greater depth.
- Perform arithmetic operations in Python.
- Use Python as a calculator to perform real-world calculations.
- Explore more advanced data types and operations.
Tasks:
1. Review of Variables and Data Types (30 mins):
- Recap variables, data types (strings, integers, floats, booleans).
- Practice variable reassignment and the impact it has on the program.
age = 20
print('Initial age:', age)
age = age + 5
print('Updated age:', age)
12
width = float(input('Enter the width of the rectangle: '))
height = float(input('Enter the height of the rectangle: '))
area = width * height
print('The area of the rectangle is:', area)
13
- Use formatted strings to display results with clarity.
- Write a Python program that takes multiple inputs from the user and displays them in a
well-formatted output.
name = 'Alice'
age = 25
height = 5.7
print('Type of name:', type(name))
print('Type of age:', type(age))
print('Type of height:', type(height))
14
print('Sum:', sum_result)
print('Product:', product)
print('Quotient:', quotient)
Assignment:
● Write a Python program that asks the user for the radius of a circle and calculates
the area using the formula: Area = π * radius^2.
15
Lab Manual for Week 1: Basic Task Input
and Output - Day 3
Day 3: Input, Output, and String Formatting
Time: 3 Hours
Learning Outcomes:
- Gain a deeper understanding of user input and output in Python.
- Learn advanced string formatting techniques.
- Build a basic Python program using multiple inputs and outputs.
Tasks:
1a. Correct Variable Naming in Python:
Variable names must start with a letter or an underscore (_), but not a number.
Variable names can only contain alphanumeric characters (A-Z, a-z, 0-9) and
underscores (_).
Variable names are case-sensitive (e.g., age and Age are different variables).
Variable names should be descriptive and concise, avoiding abbreviations where
clarity might be lost.
Avoid using Python keywords like if, else, for, class, etc., as variable names.
1) 1st_variable = "First variable"
2) @name = "John"
3) my variable = "This is wrong"
4) user-age = 25
5) total$amount = 1000
1b. Basic Input and Output (30 mins):
Review the `input()` and `print()` functions for user interaction.
- Write a Python program that asks the user for their name and age, then displays the
message using `print()`.
16
print('Your favorite color is ' + color + ' and you like to eat '
+ food + '.')
17
Explore string methods like `upper()`, `lower()`, and `title()` to manipulate input.
- Write a program that takes a sentence from the user and prints it in uppercase,
lowercase, and title case.
18
quote = input("Enter your favorite quote: ")
print(f"Your quote is: '{quote}'")
hobbies = []
for i in range(5):
hobby = input(f'Enter hobby {i+1}: ')
hobbies.append(hobby)
print('Current hobbies:', hobbies)
19
Lab Manual for Week 1: Basic Task Input
and Output - Day 4
Day 4: Conditional Statements and Loops
Time: 3 Hours
Learning Outcomes:
- Understand the use of conditional statements in Python (if, elif, else).
- Gain proficiency in loops (for and while).
- Learn how to combine loops and conditions to solve practical problems.
Tasks:
1. Simple If Statement (15 mins):
Write a Python program that checks if a number is positive and prints a message.
20
age = int(input("Enter your age: "))
membership_status = input("Are you a member (yes/no)? ").lower()
4(a). The following code is supposed to check if a number is positive, negative, or zero,
but it contains incorrect indentation. Your task is to fix the indentation so the code runs
properly.
- Teacher should teach importance of having proper indentation in python. Also,
teach about writing user-friendly and readable code.
i = 1
while i <= 10:
print(i)
i += 1
21
while True:
num = int(input('Enter a number: '))
if num == 0:
break
print(f'You entered: {num}')
total = 0
for i in range(1, 101):
total += i
print(f'The sum of numbers from 1 to 100 is {total}')
total = 0
for i in range(2, 101, 2):
23
total += i
print(f'The sum of all even numbers from 1 to 100 is {total}')
vowels = 'aeiouAEIOU'
string = input('Enter a string: ')
vowel_count = 0
for char in string:
if char in vowels:
vowel_count += 1
print(f'There are {vowel_count} vowels in the string.')
Assignment:
● Add conditional statements to your task manager to check whether tasks are
overdue, due today, or due in the future, and print appropriate messages.
24
print(f"Task '{task1_title}' is overdue! It was due on
{task1_due}.")
elif task1_due == today:
print(f"Task '{task1_title}' is due today!")
else:
print(f"Task '{task1_title}' is due in the future on {task1_due}.")
# Task 2 status check
task2_due = datetime.strptime(task2_due_date, "%Y-%m-%d").date()
if task2_due < today:
print(f"Task '{task2_title}' is overdue! It was due on
{task2_due}.")
elif task2_due == today:
print(f"Task '{task2_title}' is due today!")
else:
print(f"Task '{task2_title}' is due in the future on {task2_due}.")
# Task 3 status check
task3_due = datetime.strptime(task3_due_date, "%Y-%m-%d").date()
if task3_due < today:
print(f"Task '{task3_title}' is overdue! It was due on
{task3_due}.")
elif task3_due == today:
print(f"Task '{task3_title}' is due today!")
else:
print(f"Task '{task3_title}' is due in the future on {task3_due}.")
25
Lab Manual for Week 1: Project Day -
Day 5
Day 5: Project Day - Week 1
Time: 3 Hours
Learning Outcomes:
- Apply knowledge of basic Python programming (input, output, variables, loops, and
conditionals).
- Work on a project that brings together all the skills learned during the week.
- Practice working on a larger, structured problem that simulates real-world coding
projects.
while True:
print("\nSimple Calculator")
print("Enter 'q' to quit.")
num1 = input('Enter first number: ')
if num1 == 'q':
break
num2 = input('Enter second number: ')
operation = input('Choose operation (+, -, *, /): ')
if operation == '+':
print(f'Result: {float(num1) + float(num2)}')
elif operation == '-':
print(f'Result: {float(num1) - float(num2)}')
elif operation == '*':
print(f'Result: {float(num1) * float(num2)}')
elif operation == '/':
if float(num2) != 0:
print(f'Result: {float(num1) / float(num2)}')
else:
print("Error: Division by zero.")
26
else:
print("Invalid operation.")
import random
In this project, you'll build a personal expense tracker that allows the user to track their
daily expenses.
- The program should allow the user to add expenses with descriptions, view total expenses,
and view expenses by category (e.g., groceries, rent, etc.).
- The user should also be able to save their expense data to a file for future reference.
expenses = []
while True:
print("\nPersonal Expense Tracker")
print("1. Add a new expense")
print("2. View total expenses")
print("3. View expenses by category")
print("4. Save expenses to file")
print("5. Quit")
27
if choice == '1':
amount = float(input("Enter the expense amount: "))
category = input("Enter the category (e.g., groceries,
rent): ")
description = input("Enter a brief description: ")
expenses.append({"amount": amount, "category": category,
"description": description})
print("Expense added successfully.")
elif choice == '2':
total = sum(expense['amount'] for expense in expenses)
print(f"Total expenses: ${total:.2f}")
elif choice == '3':
category = input("Enter the category to view expenses:
")
category_expenses = [expense for expense in expenses if
expense['category'] == category]
if category_expenses:
for expense in category_expenses:
print(f"${expense['amount']:.2f} -
{expense['description']}")
else:
print(f"No expenses found for category: {category}")
elif choice == '4':
with open("expenses.txt", "w") as f:
for expense in expenses:
f.write(f"{expense['amount']},{expense['category']},{expense['descri
ption']}\n")
print("Expenses saved to file.")
elif choice == '5':
print("Exiting Expense Tracker.")
break
else:
print("Invalid option. Please choose again.")
expense_tracker()
28
Lab Manual for Week 2: Control Flow
and Looping – Day 1
Day 1: Loops – Introduction to While Loop
Time: 3 Hours
Learning Outcomes:
- Understanding what loops are and how to use them.
- Learning the syntax and usage of `while` loops in Python.
- Applying control flow statements such as `break` and `continue`.
Tasks:
1. Introduction to Loops (15 mins):
- What is a loop in programming? Explain with examples how loops allow repeating a block
of code multiple times.
# Countdown timer
num = 10
while num >= 0:
print(num)
num -= 1
print('Liftoff!')
29
print(num)
num -= 1
print('Countdown stopped before Liftoff!')
i = 1
while i <= 5:
j = 1
while j <= 5:
print(i * j, end='\t')
j += 1
print()
i += 1
# Infinite loop
counter = 0
while True:
print(f'Counter: {counter}')
counter += 1
if counter > 5:
break
30
correct_answer = 7
guess = -1
while guess != correct_answer:
guess = int(input('Guess the number (1-10): '))
print('You guessed correctly!')
flag = True
counter = 0
while flag:
print(f'Counter: {counter}')
counter += 1
if counter > 5:
flag = False
counter = 0
while counter < 5:
print(f'Counter: {counter}')
counter += 1
else:
print('Loop finished successfully!')
import random
target = random.randint(1, 10)
attempts = 3
while attempts > 0:
guess = int(input('Guess the number (1-10): '))
if guess == target:
print('Correct! You win!')
break
else:
print(f'Wrong! You have {attempts-1} attempts left.')
attempts -= 1
else:
31
print(f'Sorry, the number was {target}.')
Assignment Task:
● **Building a Countdown Timer with Custom Features** (45 mins):
- Extend the countdown timer by adding these features:
1. Allow the user to input the starting number for the countdown.
3. Allow the user to terminate the countdown at any point by pressing a specific key (e.g.,
'q').
print("Countdown ended!")
32
Lab Manual for Week 2: Control Flow
and Looping – Day 2
Day 2: Loops – Introduction to For Loop
Time: 3 Hours
Learning Outcomes:
- Understand the basics of `for` loops in Python.
- Learn how to use `range()` for looping over numbers.
- Apply `for` loops to iterate over various data structures.
Tasks:
1. Introduction to `for` Loops (15 mins):
Write a Python program that uses a `for` loop to print numbers from 1 to 10.
text = 'Python'
for char in text:
print(char)
33
Write a Python program that calculates the sum of all numbers in a list using a `for` loop.
34
Create a list of numbers and print only the even numbers using a `for` loop and `if`
condition.
numbers = [1, 2, 3, 4, 5]
for num in numbers:
if num == 10:
print('Found 10')
break
else:
print('10 not found')
35
Use list comprehension to create a list of squares of numbers from 1 to 5.
Assignment Task:
● **Creating a Number Pattern Printer** (45 mins):
- Write a Python program that uses `for` loops to print the following pattern:
1
12
123
1234
12345
36
Lab Manual for Week 2: Control Flow
and Looping – Day 3
Day 3: Combining Control Flow and Loops
Time: 3 Hours
Learning Outcomes:
- Combine control flow statements with loops.
- Learn to use nested loops and nested conditions.
- Apply loops and control flow to real-world problems like building a number-guessing
game.
Tasks:
1. Using `if` Statements in Loops (15 mins):
Write a Python program that uses a `for` loop to print only even numbers from 1 to 10.
37
print()
import random
target = random.randint(1, 20)
attempts = 5
while attempts > 0:
guess = int(input('Guess the number (1-20): '))
if guess == target:
print('Correct! You win!')
break
elif guess < target:
print('Too low!')
else:
print('Too high!')
attempts -= 1
else:
print(f'Sorry, the correct number was {target}.')
38
7. Nested Loops with Conditions (15 mins):
Write a Python program that prints a right-angled triangle pattern using nested loops and
conditions.
n = 5
for i in range(1, n+1):
for j in range(1, i+1):
print('*', end=' ')
print()
secret = 'python'
guess = ''
while guess != secret:
guess = input('Guess the secret word: ')
print('Correct! You guessed the word.')
import random
for i in range(10):
dice1 = random.randint(1, 6)
dice2 = random.randint(1, 6)
print(f'Roll {i+1}: {dice1} and {dice2}')
39
for num in range(2, 21):
is_prime = True
for i in range(2, num):
if num % i == 0:
is_prime = False
break
if is_prime:
print(f'{num} is a prime number')
num = 5
factorial = 1
for i in range(1, num + 1):
factorial *= i
print(f'The factorial of {num} is {factorial}')
14. Combining `if` and Loop for Number Patterns (15 mins):
Write a Python program that uses a nested loop and conditions to print a pattern of
numbers where each row has the same number repeated.
n = 5
for i in range(1, n+1):
for j in range(1, i+1):
print(i, end=' ')
print()
40
reversed_numbers.append(num)
print(reversed_numbers)
Assignment Task:
● **Number Guessing Game with Score Tracking** (45 mins):
- Write a Python program that builds upon the number-guessing game by adding score
tracking. The program should allow the user to play multiple rounds, keep track of the
number of attempts made, and print the score at the end.
import random
def play_game():
target = random.randint(1, 20)
attempts = 5
score = 0
while attempts > 0:
guess = int(input('Guess the number (1-20): '))
if guess == target:
print('Correct! You win!')
score += 10
break
elif guess < target:
print('Too low!')
else:
print('Too high!')
attempts -= 1
else:
print(f'Sorry, the correct number was {target}.')
return score
total_score = 0
rounds = 3
for _ in range(rounds):
total_score += play_game()
41
Lab Manual for Week 2: Control Flow
and Looping – Day 4
Day 4: Lists – Introduction and Basic Operations
Time: 3 Hours
Learning Outcomes:
- Understand how to use lists in Python.
- Learn basic list operations such as adding and removing items.
- Apply loops to iterate over lists and perform common tasks.
Tasks:
1. Introduction to Lists (15 mins):
Create a list of 5 numbers and print each number using a `for` loop.
numbers = [1, 2, 3, 4, 5]
for num in numbers:
print(num)
Create an empty list and use a loop to append numbers 1 through 5 to the list.
numbers = []
for i in range(1, 6):
numbers.append(i)
print(numbers)
Create a list of 5 fruits, and then remove 'apple' from the list.
Create a list of 5 items and print the first and last items using list indexing.
42
5. Slicing a List (15 mins):
Write a Python program that creates a list of numbers 1 to 10 and prints the first 5 numbers
using list slicing.
Create a list of student names and print each name using a `for` loop.
numbers = [5, 2, 9, 1, 7]
numbers.sort()
print(f'Sorted numbers: {numbers}')
numbers = [1, 2, 3, 4, 5]
numbers.reverse()
print(f'Reversed list: {numbers}')
Create two lists of fruits and concatenate them into one list.
43
fruits1 = ['apple', 'banana']
fruits2 = ['cherry', 'mango']
all_fruits = fruits1 + fruits2
print(all_fruits)
Create a list of numbers and use `max()` and `min()` functions to find the largest and
smallest number.
numbers = [10, 3, 5, 8, 2]
print(f'Largest number: {max(numbers)}')
print(f'Smallest number: {min(numbers)}')
Create a list with repeated items and count how many times a specific item appears in the
list.
numbers = [2, 3, 2, 5, 2, 7]
print(f'The number 2 appears {numbers.count(2)} times in the list.')
Create a nested list (a list of lists) and use a loop to print each sublist.
Assignment Task:
● **To-Do List Program with Multiple Tasks** (45 mins):
- Write a Python program that allows the user to create a to-do list with multiple tasks.
The program should allow the user to:
1. Add tasks to the list.
2. View all tasks.
3. Mark tasks as completed.
4. Remove completed tasks from the list.
# To-Do List Program
todo_list = []
44
while True:
print('\nOptions:')
print('1. Add task')
print('2. View tasks')
print('3. Mark task as completed')
print('4. Remove completed tasks')
print('5. Exit')
if choice == '1':
task = input('Enter a new task: ')
todo_list.append({'task': task, 'completed': False})
elif choice == '2':
for i, task in enumerate(todo_list):
status = 'Done' if task['completed'] else 'Not Done'
print(f'{i + 1}. {task["task"]} - {status}')
elif choice == '3':
task_number = int(input('Enter task number to mark as
completed: ')) - 1
todo_list[task_number]['completed'] = True
elif choice == '4':
todo_list = [task for task in todo_list if not
task['completed']]
elif choice == '5':
break
45
Lab Manual for Week 2: Mega Tasks
and Project Work – Day 5
Day 5: Mega Tasks and Project Incremental Work
Time: 3 Hours
Learning Outcomes:
- Solve advanced tasks combining knowledge of loops, lists, and control flow.
- Extend and apply knowledge incrementally to build a functional project.
Mega Tasks:
1. Building a Multi-List To-Do Application (30 mins):
Write a Python program that allows the user to create multiple to-do lists (e.g., work tasks,
personal tasks) and manage tasks for each list.
while True:
print("\nOptions:")
print("1. Create a new to-do list")
print("2. Add task to a list")
print("3. View tasks in a list")
print("4. Exit")
if choice == "1":
list_name = input("Enter the name of the new to-do list: ")
todo_lists[list_name] = []
elif choice == "2":
list_name = input("Enter the list name: ")
if list_name in todo_lists:
task = input("Enter a new task: ")
todo_lists[list_name].append(task)
else:
print(f"No list named {list_name}")
elif choice == "3":
list_name = input("Enter the list name: ")
if list_name in todo_lists:
print(f"Tasks in {list_name}: {todo_lists[list_name]}")
else:
print(f"No list named {list_name}")
elif choice == "4":
46
break
Write a Python program that allows the user to input a range of numbers and checks which
numbers are prime within that range.
Write a Python program that creates a 2D list (a list of lists) and performs the following
operations:
# Printing 2D List
print("Matrix:")
for row in matrix:
print(row)
# Row sums
for row in matrix:
print(f"Row sum: {sum(row)}")
# Column sums
for col in range(len(matrix[0])):
col_sum = 0
47
for row in matrix:
col_sum += row[col]
print(f"Column {col + 1} sum: {col_sum}")
Extend the number-guessing game by adding a score system that tracks how many tries the
player needed and calculates a score based on their performance.
import random
def play_game():
target = random.randint(1, 20)
attempts = 5
score = 0
while attempts > 0:
guess = int(input("Guess the number (1-20): "))
if guess == target:
print("Correct! You win!")
score += 10 * attempts
break
elif guess < target:
print("Too low!")
else:
print("Too high!")
attempts -= 1
else:
print(f"Sorry, the correct number was {target}.")
return score
total_score = 0
rounds = 3
for _ in range(rounds):
total_score += play_game()
while True:
print("\nOptions:")
print("1. Create a new to-do list")
print("2. Add task to a list")
print("3. View tasks in a list")
48
print("4. Mark task as completed")
print("5. View completed/pending tasks")
print("6. Delete a list")
print("7. Exit")
if choice == "1":
list_name = input("Enter the name of the new to-do list: ")
todo_lists[list_name] = []
elif choice == "2":
list_name = input("Enter the list name: ")
if list_name in todo_lists:
task = input("Enter a new task: ")
todo_lists[list_name].append({'task': task, 'completed':
False})
else:
print(f"No list named {list_name}")
elif choice == "3":
list_name = input("Enter the list name: ")
if list_name in todo_lists:
for task in todo_lists[list_name]:
status = "Done" if task["completed"] else "Not Done"
print(f"{task['task']} - {status}")
else:
print(f"No list named {list_name}")
elif choice == "4":
list_name = input("Enter the list name: ")
if list_name in todo_lists:
task_index = int(input("Enter the task number to mark as
completed: ")) - 1
todo_lists[list_name][task_index]["completed"] = True
elif choice == "5":
list_name = input("Enter the list name: ")
view_option = input("View completed or pending tasks (c/p)?
")
if list_name in todo_lists:
for task in todo_lists[list_name]:
if view_option == "c" and task["completed"]:
print(task["task"])
elif view_option == "p" and not task["completed"]:
print(task["task"])
elif choice == "6":
list_name = input("Enter the list name to delete: ")
if list_name in todo_lists:
del todo_lists[list_name]
print(f"Deleted list {list_name}")
elif choice == "7":
break
49
Lab Manual for Week 3: Functions and
More Data Structures – Day 1
Day 1: Introduction to Functions
Time: 3 Hours
Learning Outcomes:
- Understand what functions are and why they are useful in programming.
- Learn to define and call functions in Python.
- Explore function parameters and return values.
Tasks:
1. Defining a Simple Function (15 mins):
def greet():
print('Hello, World!')
greet()
2. Function with Parameters (15 mins):
Write a function `add_numbers(a, b)` that takes two numbers and prints their sum.
Write a function `multiply(a, b, c)` that multiplies three numbers and returns the result.
50
5. Function with Default Argument (15 mins):
Write a function `greet_user(name, greeting='Hello')` that prints a greeting with the user’s
name. The greeting should default to 'Hello' if no other greeting is provided.
Write a function `math_operations(a, b)` that returns the sum, difference, and product of
two numbers.
def sum_all(*numbers):
return sum(numbers)
print(sum_all(1, 2, 3, 4))
9. Nested Functions (15 mins):
def outer_function():
def inner_function():
print('This is the inner function.')
inner_function()
outer_function()
10. Simple Calculator Function (15 mins):
51
return a - b
elif operator == '*':
return a * b
elif operator == '/':
return a / b
else:
return 'Invalid operator'
print(calculator(10, 2, '*'))
11. Function with a List Argument (15 mins):
Write a function `print_items(items)` that takes a list and prints each item.
def print_items(items):
for item in items:
print(item)
fruits = ['apple', 'banana', 'cherry']
print_items(fruits)
12. Function to Find Maximum (15 mins):
Write a function `find_max(a, b, c)` that returns the largest of three numbers.
def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n - 1)
print(factorial(5))
14. Function with Lambda Expression (15 mins):
Write a lambda function that adds two numbers and assign it to a variable `add_lambda`.
add_lambda = lambda x, y: x + y
print(add_lambda(3, 4))
15. Function to Check Even or Odd (15 mins):
Write a function `is_even(n)` that returns `True` if the number is even and `False` otherwise.
def is_even(n):
return n % 2 == 0
print(is_even(4))
print(is_even(5))
Assignment Task:
● **Simple Banking System** (45 mins):
52
Write a Python function `bank_system()` that simulates a simple banking system. The
user can perform the following actions:
1. Check Balance
2. Deposit Money
3. Withdraw Money
4. Exit the program
The balance should start at $0 and update after each transaction.
def bank_system():
balance = 0
while True:
print("\nOptions:")
print("1. Check Balance")
print("2. Deposit Money")
print("3. Withdraw Money")
print("4. Exit")
if choice == "1":
print(f"Your balance is: ${balance}")
elif choice == "2":
amount = float(input("Enter amount to deposit: "))
balance += amount
print(f"${amount} deposited. New balance: ${balance}")
elif choice == "3":
amount = float(input("Enter amount to withdraw: "))
if amount > balance:
print("Insufficient funds!")
else:
balance -= amount
print(f"${amount} withdrawn. New balance:
${balance}")
elif choice == "4":
break
else:
print("Invalid choice")
bank_system()
53
Lab Manual for Week 3: Functions and
More Data Structures – Day 2
Day 2: Lists – Advanced Operations
Time: 3 Hours
Learning Outcomes:
- Learn advanced list operations in Python.
- Access list elements using indexing and slicing.
- Perform common operations such as sorting, reversing, and finding the length of a list.
- Practice using lists in practical scenarios.
Tasks:
1. Accessing Elements by Index (15 mins):
Write a program to print the first three elements of a list using slicing.
Write a program to print all elements from index 2 to the end of the list.
54
numbers = [10, 20, 30, 40, 50]
print(numbers[::2])
6. Sorting a List (15 mins):
Write a program to add a new element at the end of a list using `append()`.
Write a Python program to remove all elements from a list using `clear()`.
55
fruits = ['apple', 'banana', 'cherry']
if 'banana' in fruits:
print('Banana is in the list')
14. List Comprehension (15 mins):
Write a Python program to create a list of squares of numbers from 1 to 5 using list
comprehension.
Create a nested list and print the elements of each sublist using a loop.
Assignment Task:
● **Shopping List Application** (45 mins):
Write a Python program to create a shopping list. The program should allow the user to:
1. Add items to the list.
2. Remove items from the list.
3. View all items in the list.
# Shopping List Application
shopping_list = []
while True:
print("\nOptions:")
print("1. Add item")
print("2. Remove item")
print("3. View shopping list")
print("4. Exit")
if choice == "1":
item = input("Enter the item to add: ")
shopping_list.append(item)
print(f"{item} added to the list.")
elif choice == "2":
item = input("Enter the item to remove: ")
if item in shopping_list:
shopping_list.remove(item)
print(f"{item} removed from the list.")
else:
print("Item not found in the list.")
elif choice == "3":
print("Shopping List:", shopping_list)
elif choice == "4":
56
break
else:
print("Invalid choice")
57
Lab Manual for Week 3: Functions and
More Data Structures – Day 3
Day 3: Tuples and Dictionaries
Time: 3 Hours
Learning Outcomes:
- Understand how to use tuples and dictionaries in Python.
- Learn basic tuple and dictionary operations.
- Explore examples such as creating a contact list using dictionaries.
Tasks:
1. Creating a Tuple (15 mins):
Write a Python program to create a tuple with different data types (e.g., integers, strings).
58
Write a function `calculate_stats(numbers)` that takes a tuple of numbers and returns the
sum and average.
def calculate_stats(numbers):
total = sum(numbers)
avg = total / len(numbers)
return total, avg
Write a Python program to create a dictionary representing a person with keys `name`,
`age`, and `city`.
Write a Python program to access the value associated with the `name` key in a dictionary.
Write a Python program to remove the `city` key from a dictionary using `del`.
Write a Python program to loop through a dictionary and print each key and value.
Write a Python program to create a dictionary with multiple values for each key (e.g., a list
of favorite colors for each person).
59
Write a Python program to check if the key `age` exists in a dictionary.
def describe_person(person):
for key, value in person.items():
print(f'{key}: {value}')
person = {'name': 'Alice', 'age': 30, 'city': 'New York'}
describe_person(person)
15. Nested Dictionaries (15 mins):
people = {
'Alice': {'age': 30, 'city': 'New York'},
'Bob': {'age': 25, 'city': 'Chicago'}
}
print(people)
Assignment Task:
● **Contact List Application** (45 mins):
Write a Python program to create a contact list using a dictionary. The program should
allow the user to:
1. Add a contact (name, phone number).
2. View all contacts.
3. Search for a contact by name.
# Contact List Application
contacts = {}
while True:
print("\nOptions:")
print("1. Add contact")
print("2. View all contacts")
print("3. Search for a contact by name")
print("4. Exit")
60
choice = input("Choose an option: ")
if choice == "1":
name = input("Enter contact name: ")
phone = input("Enter phone number: ")
contacts[name] = phone
print(f"{name} added to contacts.")
elif choice == "2":
for name, phone in contacts.items():
print(f"{name}: {phone}")
elif choice == "3":
name = input("Enter name to search: ")
if name in contacts:
print(f"{name}: {contacts[name]}")
else:
print("Contact not found.")
elif choice == "4":
break
else:
print("Invalid choice")
61
Lab Manual for Week 3: Functions and
More Data Structures – Day 4
Day 4: Error Handling and Debugging
Time: 3 Hours
Learning Outcomes:
- Understand different types of errors in Python.
- Learn to use `try` and `except` blocks for error handling.
- Learn basic debugging techniques and how to handle user input errors.
Tasks:
1. Simple `try`-`except` Block (15 mins):
Write a Python program to handle division by zero using `try` and `except`.
try:
result = 10 / 0
except ZeroDivisionError:
print('Division by zero is not allowed.')
2. Handling Multiple Exceptions (15 mins):
Write a program to handle division by zero and invalid input using `try`-`except`.
try:
num = int(input('Enter a number: '))
result = 10 / num
except ZeroDivisionError:
print('Cannot divide by zero.')
except ValueError:
print('Invalid input. Please enter a number.')
3. Using `else` with `try` Block (15 mins):
try:
num = int(input('Enter a number: '))
result = 10 / num
except ZeroDivisionError:
print('Cannot divide by zero.')
else:
print(f'Result: {result}')
62
4. Using `finally` Block (15 mins):
Write a program with a `finally` block to ensure a message is printed whether an error
occurs or not.
try:
num = int(input('Enter a number: '))
result = 10 / num
except ZeroDivisionError:
print('Cannot divide by zero.')
finally:
print('End of program.')
5. Raising Exceptions (15 mins):
Write a Python program that raises a custom exception when a specific condition is met.
def check_age(age):
if age < 18:
raise ValueError('Age must be at least 18.')
else:
print('Access granted.')
try:
check_age(15)
except ValueError as e:
print(e)
6. Debugging with Print Statements (15 mins):
Write a Python program and insert print statements at different points to trace its
execution.
Write a Python program that handles the `FileNotFoundError` when trying to open a non-
existent file.
try:
file = open('non_existent_file.txt')
except FileNotFoundError:
print('File not found.')
8. Handling Invalid Input in a Loop (15 mins):
Write a program that continuously asks for a number until the user provides valid input.
while True:
try:
63
num = int(input('Enter a number: '))
break
except ValueError:
print('Invalid input. Please enter a number.')
9. Catching Multiple Exception Types (15 mins):
try:
num = int(input('Enter a number: '))
result = 10 / num
except (ValueError, ZeroDivisionError):
print('Error: invalid input or division by zero.')
10. Using Assertions (15 mins):
def check_positive(num):
assert num > 0, 'Number must be positive.'
print(f'{num} is positive.')
check_positive(10)
# check_positive(-5) # This will raise an AssertionError
11. Custom Exception Handling (15 mins):
class NegativeNumberError(Exception):
pass
try:
num = int(input('Enter a positive number: '))
if num < 0:
raise NegativeNumberError('Negative number entered.')
except NegativeNumberError as e:
print(e)
12. Using `try`-`except` for Dictionary Lookup (15 mins):
Write a program that handles key errors when looking up a key in a dictionary.
import pdb
64
pdb.set_trace()
return a + b
Write a Python program that handles an `IndexError` when accessing an invalid index in a
list.
my_list = [1, 2, 3]
try:
print(my_list[5])
except IndexError:
print('Index out of range.')
15. Logging Errors (15 mins):
Write a Python program that logs error messages to a file using the `logging` module.
import logging
logging.basicConfig(filename='error.log', level=logging.ERROR)
try:
result = 10 / 0
except ZeroDivisionError as e:
logging.error('Division by zero occurred.')
Assignment Task:
● **Handling User Input Errors Gracefully** (45 mins):
Write a Python program that continuously asks the user for two numbers and an operator
(`+`, `-`, `*`, `/`). The program should handle the following errors:
1. Invalid number input (e.g., inputting a string instead of a number).
2. Division by zero.
3. Invalid operator (i.e., operator not in `+`, `-`, `*`, `/`).
The program should display the result of the operation if valid inputs are provided.
def calculator():
while True:
try:
num1 = float(input('Enter the first number: '))
num2 = float(input('Enter the second number: '))
operator = input('Enter the operator (+, -, *, /): ')
if operator == '+':
result = num1 + num2
elif operator == '-':
result = num1 - num2
elif operator == '*':
result = num1 * num2
elif operator == '/':
result = num1 / num2
65
else:
raise ValueError('Invalid operator')
print(f'Result: {result}')
break
except ValueError as e:
print(f'Error: {e}. Please try again.')
except ZeroDivisionError:
print('Error: Cannot divide by zero.')
calculator()
66
Lab Manual for Week 3: Mega Tasks
and Project Work – Day 5
Day 5: Mega Tasks and Project Incremental Work
Time: 3 Hours
Learning Outcomes:
- Solve advanced tasks combining knowledge of functions, lists, tuples, and dictionaries.
- Extend and apply knowledge incrementally to build a functional project.
Mega Tasks:
1. Contact Management System (45 mins):
Write a Python program that uses functions to add, delete, and search for contacts in a
dictionary. Each contact should have a name, phone number, and email address.
def delete_contact(name):
if name in contacts:
del contacts[name]
print(f'{name} has been deleted.')
else:
print(f'{name} not found.')
def search_contact(name):
if name in contacts:
print(f"Name: {name}, Phone: {contacts[name]['phone']},
Email: {contacts[name]['email']}")
else:
print(f'{name} not found.')
# Example usage
add_contact('Alice', '123-456', '[email protected]')
add_contact('Bob', '789-012', '[email protected]')
search_contact('Alice')
67
delete_contact('Bob')
Write a program that asks the user to enter two numbers and performs division. The
program should handle invalid input and division by zero using try-except blocks.
def divide_numbers():
try:
num1 = float(input("Enter the first number: "))
num2 = float(input("Enter the second number: "))
result = num1 / num2
print(f"Result: {result}")
except ValueError:
print("Invalid input. Please enter numbers.")
except ZeroDivisionError:
print("Cannot divide by zero.")
divide_numbers()
Write a function `tuple_operations()` that takes a tuple of numbers, finds the maximum,
minimum, and sum, and returns these values.
def tuple_operations(numbers):
max_num = max(numbers)
min_num = min(numbers)
total = sum(numbers)
return max_num, min_num, total
Write a function `list_operations()` that takes a list of numbers, sorts the list, reverses it, and
returns the modified list.
def list_operations(numbers):
numbers.sort()
numbers.reverse()
return numbers
68
Project Incremental Work:
Continue refining the contact management system by adding the following features:
- Add error handling for duplicate contact names.
- Allow the user to update an existing contact's phone number and email address.
# Contact Management System with Updates and Error Handling
contacts = {}
def delete_contact(name):
if name in contacts:
del contacts[name]
print(f'{name} has been deleted.')
else:
print(f'{name} not found.')
def search_contact(name):
if name in contacts:
print(f"Name: {name}, Phone: {contacts[name]['phone']},
Email: {contacts[name]['email']}")
else:
print(f'{name} not found.')
# Example usage
add_contact('Alice', '123-456', '[email protected]')
add_contact('Bob', '789-012', '[email protected]')
update_contact('Alice', '555-999', '[email protected]')
search_contact('Alice')
delete_contact('Bob')
69
Lab Manual for Week 4: File Handling
and Basic Project Structuring – Day 1
Day 1: Introduction to File Handling
Time: 3 Hours
Learning Outcomes:
- Understand why storing data in files is essential.
- Learn how to open, read, write, and close files in Python.
- Practice file handling through practical exercises.
Tasks:
1. Creating and Writing to a File (15 mins):
Write a Python program that creates a text file and writes a simple message into it.
Write a program that reads the contents of a text file and prints them.
Write a program that reads a file line by line and prints each line.
70
print(line.strip())
file.close()
5. Appending to a File (15 mins):
Write a program to open a file using the `with` statement to ensure the file is properly
closed.
Write a program that writes numbers 1 to 5 into a file, each on a new line.
Write a program that reads the numbers from `numbers.txt` and prints them.
Write a program that checks if a file exists before trying to open it.
import os
if os.path.exists('example.txt'):
with open('example.txt', 'r') as file:
print(file.read())
else:
print('File does not exist.')
10. Handling FileNotFoundError (15 mins):
Write a program that handles the `FileNotFoundError` when trying to open a non-existent
file.
try:
with open('non_existent.txt', 'r') as file:
print(file.read())
except FileNotFoundError:
print('File not found.')
11. Writing and Reading Lists to a File (15 mins):
71
Write a program that writes a list of strings to a file and then reads them back.
Write a program that reads a text file and counts the number of words in it.
Write a program that demonstrates the use of `seek()` and `tell()` methods while working
with a file.
Assignment Task:
● **Simple Text Editor** (45 mins):
Write a Python program that simulates a simple text editor with the following
functionalities:
1. Create a new text file.
2. Append text to an existing file.
3. Display the contents of a file.
4. Exit the program.
72
def text_editor():
while True:
print("\nOptions:")
print("1. Create a new file")
print("2. Append to an existing file")
print("3. Display file contents")
print("4. Exit")
if choice == "1":
filename = input("Enter the filename: ")
content = input("Enter text to write: ")
with open(filename, 'w') as file:
file.write(content)
print(f"File '{filename}' created.")
text_editor()
73
Lab Manual for Week 4: File Handling
and Basic Project Structuring – Day 2
Day 2: Working with Files (Continued)
Time: 3 Hours
Learning Outcomes:
- Understand how to append data to files in Python.
- Learn to handle common file errors such as `FileNotFoundError`.
- Practice file handling through practical examples, including saving user data to files.
Tasks:
1. Appending Data to a File (15 mins):
Write a Python program that appends a new line of text to an existing file.
Write a program to read the contents of a file after appending data to it.
Write a Python program that asks the user for input and writes it to a file. If the file exists,
append to it; otherwise, create a new file.
Write a Python program that handles `FileNotFoundError` when trying to open a non-
existent file.
try:
with open('non_existent_file.txt', 'r') as file:
print(file.read())
74
except FileNotFoundError:
print('File not found.')
Write a program that checks if a file exists before trying to read it.
import os
if os.path.exists('example.txt'):
with open('example.txt', 'r') as file:
print(file.read())
else:
print('File does not exist.')
import os
if os.path.exists('example.txt'):
os.remove('example.txt')
print('File deleted.')
else:
print('File does not exist.')
Write a Python program that reads data from one file and writes it to another file.
Write a program that asks the user for their name and age, then saves this information to a
file.
75
with open('user_info.txt', 'a') as file:
file.write(f'Name: {name}, Age: {age}\n')
Write a program that reads the contents of a file and displays it on the screen.
Write a program that asks for a filename to read and handles the `FileNotFoundError` if the
file doesn't exist.
Write a Python program that appends numbers from 1 to 10 to a file, each on a new line.
Write a program that asks the user for multiple lines of input and appends each line to a file.
lines = []
for _ in range(3):
line = input('Enter a line of text: ')
lines.append(line)
with open('user_input.txt', 'a') as file:
for line in lines:
file.write(line + '\n')
76
15. Combining Read and Write Operations (15 mins):
Write a program that reads the contents of a file, modifies it, and writes the updated content
back to the file.
Assignment Task:
● **User Data Storage System** (45 mins):
Write a Python program that simulates a basic user data storage system. The program
should allow the user to:
def user_data_storage():
while True:
print("\nOptions:")
print("1. Add new user data")
print("2. View all user data")
print("3. Append to existing user data")
print("4. Exit")
if choice == "1":
name = input("Enter name: ")
age = input("Enter age: ")
email = input("Enter email: ")
with open('user_data.txt', 'a') as file:
file.write(f'Name: {name}, Age: {age}, Email:
{email}\n')
print("User data saved.")
77
except FileNotFoundError:
print("No user data found.")
user_data_storage()
78
Lab Manual for Week 4: File Handling
and Basic Project Structuring – Day 3
Day 3: Structuring a Python Project
Time: 3 Hours
Learning Outcomes:
- Learn how to structure a Python project with modules and functions.
- Organize code into reusable components.
- Explore how to import code from other files and create basic Python packages.
Tasks:
1. Organizing Code into Functions (15 mins):
Write a Python function `greet()` that prints a greeting message. Call the function multiple
times in the script.
def greet():
print('Hello, welcome to the Python project!')
# Calling the function multiple times
greet()
greet()
def greet():
print('Hello, welcome to the Python project!')
# Save this code in a file called 'greetings.py'
Write a new Python script that imports the `greet()` function from `greetings.py` and calls it.
79
Write a Python function `add_numbers(a, b)` that takes two numbers as input and returns
their sum. Save this function in `math_utils.py`.
Write a script that imports `greet()` from `greetings.py` and `add_numbers()` from
`math_utils.py`.
greet()
result = add_numbers(5, 10)
print(f'The sum is: {result}')
Modify the `add_numbers()` function in `math_utils.py` so that it only runs when the file is
executed directly.
if __name__ == '__main__':
result = add_numbers(10, 20)
print(f'The sum is: {result}')
Create a folder named `utilities`, and place `greetings.py` and `math_utils.py` inside it. Create
an empty `__init__.py` file inside the folder to make it a package.
Write a script that imports the functions `greet()` and `add_numbers()` from the `utilities`
package.
80
from utilities.greetings import greet
from utilities.math_utils import add_numbers
greet()
print(add_numbers(10, 15))
def capitalize_text(text):
return text.capitalize()
greet()
result = add_numbers(7, 8)
print(f'Sum: {result}')
print(capitalize_text('hello world'))
Modify your package to use relative imports for importing `add_numbers()` inside the
`greetings.py` file.
Create a new file `file_utils.py` that contains a function `read_file(filename)` to read and
print the contents of a file.
def read_file(filename):
with open(filename, 'r') as file:
content = file.read()
81
print(content)
Write a script that imports `read_file()` from `file_utils.py` and reads the contents of a file.
read_file('example.txt')
Write a Python script that combines the functions from all the modules created so far into a
single script that performs a greeting, a calculation, and a file read.
greet()
print(add_numbers(5, 10))
read_file('example.txt')
Write a `README.md` file for the Python project you have created, explaining how to use
each module and function.
# Python Project
This project contains modules for greetings, math operations, string
manipulation, and file handling.
## How to Use
1. Import the functions from the respective modules.
2. Call the functions as needed.
Assignment Task:
● **Modularized To-Do List Application** (45 mins):
Write a Python program to modularize the To-Do List application. The application should
allow the user to:
82
3. Delete a task from the list.
The program should be divided into multiple files: one for handling tasks, one for file
operations (saving/loading tasks), and one for the main logic.
# tasks.py
tasks = []
def add_task(task):
tasks.append(task)
def view_tasks():
for i, task in enumerate(tasks, 1):
print(f'{i}. {task}')
def delete_task(task_number):
if 0 < task_number <= len(tasks):
tasks.pop(task_number - 1)
# file_utils.py
def save_tasks(filename):
with open(filename, 'w') as file:
for task in tasks:
file.write(task + '\n')
def load_tasks(filename):
with open(filename, 'r') as file:
global tasks
tasks = file.read().splitlines()
# main.py
from tasks import add_task, view_tasks, delete_task
from file_utils import save_tasks, load_tasks
while True:
print("\n1. Add Task")
print("2. View Tasks")
print("3. Delete Task")
print("4. Save Tasks")
print("5. Load Tasks")
print("6. Exit")
if choice == "1":
task = input("Enter a task: ")
83
add_task(task)
elif choice == "2":
view_tasks()
elif choice == "3":
task_number = int(input("Enter task number to delete: "))
delete_task(task_number)
elif choice == "4":
save_tasks('tasks.txt')
print("Tasks saved.")
elif choice == "5":
load_tasks('tasks.txt')
print("Tasks loaded.")
elif choice == "6":
break
else:
print("Invalid choice")
84
Lab Manual for Week 4: File Handling
and Basic Project Structuring – Day 4
Day 4: Project Day Preparation
Time: 3 Hours
Learning Outcomes:
- Review key concepts of file handling and modularization.
- Refactor a Python project for better structure and organization.
- Implement file storage for project data, allowing persistence across sessions.
Tasks:
1. Reviewing File Handling Basics (15 mins):
Write a simple program that creates a text file and writes a message into it.
def read_file(filename):
with open(filename, 'r') as file:
85
return file.read()
print(read_file('example.txt'))
def load_tasks(filename):
with open(filename, 'r') as file:
return file.read().splitlines()
tasks = load_tasks('tasks.txt')
print(tasks)
86
11. Handling File Errors (15 mins):
Write a program that handles `FileNotFoundError` when trying to load tasks from a non-
existent file.
try:
tasks = load_tasks('non_existent_file.txt')
except FileNotFoundError:
print('File not found.')
if __name__ == '__main__':
tasks = ['Sample task']
save_tasks(tasks, 'tasks.txt')
def load_tasks(filename):
print(f'Loading tasks from {filename}')
with open(filename, 'r') as file:
return file.read().splitlines()
# README.md content:
Assignment Task:
● **Refactoring the To-Do List Project** (45 mins):
Refactor the To-Do List project so that:
87
# main.py
from tasks import add_task, view_tasks, delete_task
from file_utils import save_tasks, load_tasks
if __name__ == '__main__':
tasks = load_tasks('tasks.txt')
while True:
print("\n1. Add Task")
print("2. View Tasks")
print("3. Delete Task")
print("4. Save Tasks")
print("5. Exit")
if choice == "1":
task = input("Enter a task: ")
add_task(task)
elif choice == "2":
view_tasks()
elif choice == "3":
task_number = int(input("Enter task number to delete:
"))
delete_task(task_number)
elif choice == "4":
save_tasks(tasks, 'tasks.txt')
elif choice == "5":
break
else:
print("Invalid choice")
88
Lab Manual for Week 4: File Handling
and Basic Project Structuring – Day 5
Day 5: Mega Tasks and Project Work
Time: 3 Hours
Learning Outcomes:
- Apply file handling and project structuring concepts learned throughout the week.
- Implement incremental project changes and mega tasks that integrate file storage and
modular design.
Mega Tasks:
1. Enhanced To-Do List with File Storage (45 mins):
Write a Python program that allows users to add, view, and delete tasks. Tasks should be
stored in a file so that they persist between program runs.
def add_task(task):
tasks.append(task)
def view_tasks():
for i, task in enumerate(tasks, 1):
print(f'{i}. {task}')
def delete_task(task_number):
if 0 < task_number <= len(tasks):
tasks.pop(task_number - 1)
def save_tasks(filename):
with open(filename, 'w') as file:
for task in tasks:
file.write(task + '\n')
def load_tasks(filename):
with open(filename, 'r') as file:
global tasks
tasks = file.read().splitlines()
if __name__ == '__main__':
89
try:
load_tasks('tasks.txt')
except FileNotFoundError:
print('No existing tasks found.')
while True:
print("\n1. Add Task")
print("2. View Tasks")
print("3. Delete Task")
print("4. Save and Exit")
def load_tasks(filename):
with open(filename, 'r') as file:
return file.read().splitlines()
90
def add_task(task):
tasks.append(task)
def view_tasks():
for i, task in enumerate(tasks, 1):
print(f'{i}. {task}')
def delete_task(task_number):
if 0 < task_number <= len(tasks):
tasks.pop(task_number - 1)
if __name__ == '__main__':
tasks = []
try:
tasks = load_tasks('tasks.txt')
except FileNotFoundError:
print('No existing tasks found.')
while True:
print("\n1. Add Task")
print("2. View Tasks")
print("3. Delete Task")
print("4. Save and Exit")
91
Add error handling to ensure that the program behaves correctly if the file is not found or
cannot be opened.
def load_tasks(filename):
try:
with open(filename, 'r') as file:
return file.read().splitlines()
except FileNotFoundError:
print("No tasks found. Starting with an empty list.")
return []
except IOError as e:
print(f"An error occurred while loading tasks: {e}")
return []
if __name__ == '__main__':
tasks = []
try:
tasks = load_tasks('tasks.txt')
92
except FileNotFoundError:
print('No existing tasks found.')
while True:
print("\n1. Add Task")
print("2. View Tasks")
print("3. Delete Task")
print("4. Search Task")
print("5. Save and Exit")
93
Lab Manual for Week 5: Introduction to
Object-Oriented Programming – Day 1
Day 1: Introduction to Classes and Objects
Time: 3 Hours
Learning Outcomes:
- Understand the basic concepts of Object-Oriented Programming (OOP).
- Learn how to define a class and create objects.
- Understand object attributes and methods.
Tasks:
1. What is Object-Oriented Programming? (15 mins):
Discuss what Object-Oriented Programming (OOP) is and its key concepts such as classes,
objects, and methods.
class Car:
def __init__(self, brand, model):
self.brand = brand
self.model = model
# Create an object
my_car = Car('Toyota', 'Corolla')
print(f'My car is a {my_car.brand} {my_car.model}')
class Car:
def __init__(self, brand, model):
self.brand = brand
self.model = model
def start_engine(self):
print(f'The {self.brand} {self.model}\'s engine has
started.')
94
my_car = Car('Toyota', 'Corolla')
my_car.start_engine()
car1.start_engine()
car2.start_engine()
class Student:
def __init__(self, name, age):
self.name = name
self.age = age
def introduce(self):
print(f'Hi, I am {self.name} and I am {self.age} years
old.')
student.age = 21
student.introduce() # Now the age should be 21
class Task:
def __init__(self, title):
self.title = title
self.completed = False
def mark_complete(self):
self.completed = True
print(f'Task {self.title} is marked as completed.')
95
# Create a task object and mark it as complete
task1 = Task('Finish homework')
task1.mark_complete()
def show_tasks(tasks):
for task in tasks:
status = 'Completed' if task.completed else 'Incomplete'
print(f'{task.title}: {status}')
show_tasks(tasks)
class Task:
def __init__(self, title):
self.title = title
self.completed = False
def mark_complete(self):
self.completed = True
def show_status(self):
status = 'Completed' if self.completed else 'Incomplete'
print(f'Task {self.title} is {status}.')
tasks = []
def create_task():
title = input('Enter task title: ')
96
task = Task(title)
tasks.append(task)
print(f'Task {title} created.')
Assignment Task:
● **Simple Task Management System** (45 mins):
Write a Python program that simulates a simple task management system using OOP. The
program should allow the user to:
class Task:
def __init__(self, title):
self.title = title
self.completed = False
def mark_complete(self):
self.completed = True
def show_status(self):
status = 'Completed' if self.completed else 'Incomplete'
print(f'Task {self.title} is {status}.')
tasks = []
def create_task():
title = input('Enter task title: ')
task = Task(title)
tasks.append(task)
def view_tasks():
for i, task in enumerate(tasks, 1):
task.show_status()
def mark_task_completed():
task_number = int(input('Enter task number to mark complete: '))
if 0 < task_number <= len(tasks):
tasks[task_number - 1].mark_complete()
97
while True:
print("\n1. Add Task")
print("2. View Tasks")
print("3. Mark Task as Completed")
print("4. Exit")
if choice == "1":
create_task()
elif choice == "2":
view_tasks()
elif choice == "3":
mark_task_completed()
elif choice == "4":
break
else:
print("Invalid choice")
98
Lab Manual for Week 5: Object-Oriented
Programming – Day 2
Day 2: More on Classes and Methods
Time: 3 Hours
Learning Outcomes:
Practice managing objects and interacting with object attributes and methods
Tasks:
2. 1. Defining a Constructor Method (__init__) (15 mins):
- Define a class Person with attributes name and age. Initialize these attributes using a
constructor method.
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
person1 = Person('John', 30)
print(f'{person1.name} is {person1.age} years old.')
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def greet(self):
print(f'Hello, my name is {self.name}.')
person1.greet()
99
class Person:
species = 'Human'
print(Person.species))
class Task:
def __init__(self, title):
self.title = title
self.completed = False
def mark_complete(self):
self.completed = True
print(f'Task {self.title} is marked as completed.')
- Add a method show_status() to the Task class that prints whether the task is completed
class Task:
def __init__(self, title):
self.title = title
self.completed = False
def show_status(self):
status = 'Completed' if self.completed else 'Incomplete'
print(f'Task {self.title} is {status}.')
task1.show_status()
- Create multiple Task objects and store them in a list. Write a function to display all tasks
and their status.
100
tasks = [Task('Finish homework'), Task('Go shopping'), Task('Read a
book')]
def show_tasks(tasks):
for task in tasks:
task.show_status()
show_tasks(tasks)
class Task:
def __init__(self, title, due_date):
self.title = title
self.due_date = due_date
self.completed = False
def show_due_date(self):
print(f'Task {self.title} is due on {self.due_date}.')
class Task:
def __init__(self, title, due_date):
self.title = title
self.due_date = due_date
self.completed = False
def __str__(self):
status = 'Completed' if self.completed else 'Incomplete'
return f'Task: {self.title}, Due: {self.due_date}, Status:
{status}'
class Task:
def __init__(self, title, due_date):
101
self.title = title
self.due_date = due_date
task1.update_title('Complete assignment')
print(task1)
for _ in range(3):
title = input('Enter task title: ')
due_date = input('Enter due date: ')
task = Task(title, due_date)
tasks.append(task)
11. Marking Task Completion from User Input (20 mins):
- Extend the program to allow users to mark tasks as completed by entering the task
number.
def mark_task_completed(tasks):
task_number = int(input('Enter task number to mark complete: '))
if 0 < task_number <= len(tasks):
tasks[task_number - 1].mark_complete()
mark_task_completed(tasks)
102
14. Task Search by Keyword (20 mins):
- Add a search function that allows users to search for tasks by keyword.
def search_task(keyword):
for task in tasks:
if keyword.lower() in task.title.lower():
print(task)
Assignment Task:
Task Management System (45 mins):- Extend the countdown timer by adding these
features:
class Task:
def __init__(self, title, due_date, priority):
self.title = title
self.due_date = due_date
self.priority = priority
self.completed = False
103
def mark_complete(self):
self.completed = True
def show_task(self):
status = 'Completed' if self.completed else 'Incomplete'
print(f'Task: {self.title}, Due: {self.due_date}, Priority:
{self.priority}, Status: {status}')
tasks = []
def create_task():
title = input("Enter task title: ")
due_date = input("Enter due date (YYYY-MM-DD): ")
priority = input("Enter priority (Low, Medium, High): ")
task = Task(title, due_date, priority)
tasks.append(task)
def view_tasks():
if not tasks:
print("No tasks available.")
else:
for i, task in enumerate(tasks, 1):
print(f"Task {i}:")
task.show_task()
print("")
def mark_task_completed():
view_tasks()
task_number = int(input("Enter the task number to mark as
completed: "))
if 0 < task_number <= len(tasks):
tasks[task_number - 1].mark_complete()
print("Task marked as completed.")
else:
print("Invalid task number.")
def save_tasks(filename="tasks.txt"):
with open(filename, 'w') as file:
for task in tasks:
task_line =
f"{task.title},{task.due_date},{task.priority},{task.completed}\n"
file.write(task_line)
print("Tasks saved successfully.")
104
def load_tasks(filename="tasks.txt"):
try:
with open(filename, 'r') as file:
for line in file:
title, due_date, priority, completed =
line.strip().split(',')
task = Task(title, due_date, priority)
task.completed = completed == 'True'
tasks.append(task)
print("Tasks loaded successfully.")
except FileNotFoundError:
print("No saved tasks found.")
def main():
while True:
print("\nTask Management System")
print("1. Add a new task")
print("2. View all tasks")
print("3. Mark a task as completed")
print("4. Save tasks to file")
print("5. Load tasks from file")
print("6. Exit")
if __name__ == "__main__":
main()
105
Lab Manual for Week 5: Object-Oriented
Programming – Day 3
Day 3: Inheritance and Polymorphism
Time: 3 Hours
Learning Outcomes:
- Understand class inheritance and how to create child classes.
- Learn about method overriding and polymorphism.
- Practice creating a task management system with inheritance.
Tasks:
1. Creating a Base Class (15 mins):
Create a class `Animal` with attributes `name` and `species`. Add a method `make_sound()`.
class Animal:
def __init__(self, name, species):
self.name = name
self.species = species
def make_sound(self):
print('Animal sound')
# Create an object
animal1 = Animal('Lion', 'Mammal')
animal1.make_sound()
2. Creating a Child Class (15 mins):
Create a class `Dog` that inherits from `Animal` and overrides `make_sound()`.
class Dog(Animal):
def make_sound(self):
print('Bark')
class Dog(Animal):
def __init__(self, name, species, breed):
super().__init__(name, species)
106
self.breed = breed
def make_sound(self):
super().make_sound()
print('Bark')
class Cat(Animal):
def make_sound(self):
print('Meow')
def animal_sound(animal):
animal.make_sound()
class Dog(Animal):
def play(self):
print(f'{self.name} is playing.')
class Dog(Animal):
def make_sound(self):
super().make_sound()
print('Woof')
107
# Test method overriding
dog1.make_sound()
8. Adding Attributes to Child Class (15 mins):
Add a new attribute `age` to the `Dog` class and initialize it using `__init__()`.
class Dog(Animal):
def __init__(self, name, species, breed, age):
super().__init__(name, species)
self.breed = breed
self.age = age
class Puppy(Dog):
def train(self):
print(f'{self.name} is being trained.')
class Vehicle:
def __init__(self, make, model):
self.make = make
self.model = model
def start_engine(self):
print('Engine started')
class Car(Vehicle):
def __init__(self, make, model, year):
super().__init__(make, model)
self.year = year
108
car1 = Car('Honda', 'Civic', 2020)
print(car1.year)
12. Overriding a Method in Child Class (15 mins):
Override the `start_engine()` method in the `Car` class.
class Car(Vehicle):
def start_engine(self):
print('Car engine started')
class Car(Vehicle):
def drive(self):
print(f'{self.make} {self.model} is driving.')
class ElectricVehicle:
def charge_battery(self):
print('Battery charging...')
def vehicle_info(vehicle):
vehicle.start_engine()
vehicle.drive()
109
Assignment Task:
● **Task Management System with Inheritance** (45 mins):
Extend the Task Management System with the following:
1. Create a base class `Task` with attributes `title`, `due_date`, and `priority`.
2. Create a child class `ProjectTask` that inherits from `Task` and adds an attribute
`project_name`.
3. Override the method to display task details in the `ProjectTask` class to include the
project name.
4. Write a function that accepts both `Task` and `ProjectTask` objects and displays their
details.
class Task:
def __init__(self, title, due_date, priority):
self.title = title
self.due_date = due_date
self.priority = priority
def display_details(self):
print(f"Task: {self.title}, Due Date: {self.due_date},
Priority: {self.priority}")
# Example usage
task1 = Task("Complete report", "2024-09-15", "High")
110
project_task1 = ProjectTask("Design module", "2024-09-20", "Medium",
"Website Redesign")
# Display details
display_task_details(task1)
display_task_details(project_task1)
111
Lab Manual for Week 5: Object-Oriented
Programming – Day 4
Day 4: Working with Objects in the Project
Time: 3 Hours
Learning Outcomes:
- Refactor code to use object-oriented principles.
- Manage objects as task representations in a project.
- Practice updating, removing, and managing objects in a task management system.
Tasks:
1. Refactoring Code to Use Classes (15 mins):
Refactor your previous task management system to use the `Task` class for representing
individual tasks.
class Task:
def __init__(self, title, due_date, priority):
self.title = title
self.due_date = due_date
self.priority = priority
class Task:
def __init__(self, title, due_date, priority):
self.title = title
self.due_date = due_date
self.priority = priority
self.completed = False
def mark_complete(self):
self.completed = True
class Task:
def show_status(self):
112
status = 'Completed' if self.completed else 'Incomplete'
print(f'{self.title}: {status}')
tasks = []
def add_task():
title = input('Enter task title: ')
due_date = input('Enter due date: ')
priority = input('Enter priority: ')
task = Task(title, due_date, priority)
tasks.append(task)
def view_tasks():
for task in tasks:
task.show_status()
def mark_task_completed():
task_num = int(input('Enter task number to mark complete: '))
if 0 < task_num <= len(tasks):
tasks[task_num - 1].mark_complete()
def remove_task():
task_num = int(input('Enter task number to remove: '))
if 0 < task_num <= len(tasks):
tasks.pop(task_num - 1)
def search_task_by_title(title):
for task in tasks:
if task.title.lower() == title.lower():
task.show_status()
113
tasks.sort(key=lambda task: task.due_date)
view_tasks()
def update_task(task_num):
new_title = input('Enter new title: ')
new_due_date = input('Enter new due date: ')
tasks[task_num - 1].title = new_title
tasks[task_num - 1].due_date = new_due_date
def save_tasks_to_file(filename='tasks.txt'):
with open(filename, 'w') as file:
for task in tasks:
file.write(f'{task.title},{task.due_date},{task.priority},{task.c
ompleted}\n')
def load_tasks_from_file(filename='tasks.txt'):
with open(filename, 'r') as file:
for line in file:
title, due_date, priority, completed =
line.strip().split(',')
task = Task(title, due_date, priority)
task.completed = completed == 'True'
tasks.append(task)
def show_completed_tasks():
for task in tasks:
if task.completed:
task.show_status()
def show_incomplete_tasks():
for task in tasks:
114
if not task.completed:
task.show_status()
def exit_program():
save_tasks_to_file()
print('Tasks saved. Exiting program.')
exit()
Assignment Task:
● **Task Management System with Object-Oriented Refactoring** (45 mins):
Refactor the task management system to perform the following:
3. Implement file saving and loading to store and retrieve tasks between sessions.
4. Sort tasks by due date and filter them based on completion status.
import os
def mark_complete(self):
self.completed = True
def show_task(self):
115
status = "Completed" if self.completed else "Incomplete"
print(f"Task: {self.title}, Due: {self.due_date},
Priority: {self.priority}, Status: {status}")
def add_task(self):
title = input("Enter task title: ")
due_date = input("Enter task due date (YYYY-MM-DD): ")
priority = input("Enter task priority (Low, Medium,
High): ")
task = Task(title, due_date, priority)
self.tasks.append(task)
def update_task(self):
self.view_tasks()
task_num = int(input("Enter task number to update: "))
if 0 < task_num <= len(self.tasks):
task = self.tasks[task_num - 1]
new_title = input(f"Enter new title (leave blank to
keep '{task.title}'): ")
new_due_date = input(f"Enter new due date (leave
blank to keep '{task.due_date}'): ")
new_priority = input(f"Enter new priority (leave
blank to keep '{task.priority}'): ")
task.update_task(new_title or None, new_due_date or
None, new_priority or None)
print("Task updated successfully.")
else:
print("Invalid task number.")
def delete_task(self):
self.view_tasks()
task_num = int(input("Enter task number to delete: "))
if 0 < task_num <= len(self.tasks):
self.tasks.pop(task_num - 1)
print("Task deleted successfully.")
else:
print("Invalid task number.")
def search_task(self):
116
search_term = input("Enter task title to search:
").lower()
for task in self.tasks:
if search_term in task.title.lower():
task.show_task()
def view_tasks(self):
if not self.tasks:
print("No tasks available.")
else:
for i, task in enumerate(self.tasks, 1):
print(f"Task {i}:")
task.show_task()
def mark_task_completed(self):
self.view_tasks()
task_num = int(input("Enter task number to mark as
completed: "))
if 0 < task_num <= len(self.tasks):
self.tasks[task_num - 1].mark_complete()
print("Task marked as completed.")
else:
print("Invalid task number.")
def show_completed_tasks(self):
for task in self.tasks:
if task.completed:
task.show_task()
def show_incomplete_tasks(self):
for task in self.tasks:
if not task.completed:
task.show_task()
def sort_tasks_by_due_date(self):
self.tasks.sort(key=lambda task: task.due_date)
print("Tasks sorted by due date.")
117
task_line =
f"{task.title},{task.due_date},{task.priority},{task.completed}\n
"
file.write(task_line)
print(f"Tasks saved to {filename}.")
def run(self):
while True:
print("\nTask Management System")
print("1. Add Task")
print("2. Update Task")
print("3. Delete Task")
print("4. Search Task")
print("5. View All Tasks")
print("6. Mark Task as Completed")
print("7. View Completed Tasks")
print("8. View Incomplete Tasks")
print("9. Sort Tasks by Due Date")
print("10. Save Tasks to File")
print("11. Load Tasks from File")
print("12. Exit")
118
self.search_task()
elif choice == "5":
self.view_tasks()
elif choice == "6":
self.mark_task_completed()
elif choice == "7":
self.show_completed_tasks()
elif choice == "8":
self.show_incomplete_tasks()
elif choice == "9":
self.sort_tasks_by_due_date()
elif choice == "10":
self.save_tasks()
elif choice == "11":
self.load_tasks()
elif choice == "12":
print("Exiting the Task Management System.")
break
else:
print("Invalid choice. Please try again.")
if __name__ == "__main__":
task_system = TaskManagementSystem()
task_system.run()
119
Lab Manual for Week 5: Object-Oriented
Programming – Day 5
Day 5: Project Day – Advanced Task Management System
Time: 3 Hours
Learning Outcomes:
- Apply object-oriented programming concepts to a full-fledged project.
- Implement task and project management systems using classes, inheritance, and file I/O.
- Develop a functional Task Management System with advanced features.
Mega Tasks:
1. Refactoring Task Management with Inheritance (45 mins):
Refactor the Task Management System to create a base class `Task` and a child class
`ProjectTask`. Include the project name in tasks related to a project.
class ProjectTask(Task):
def __init__(self, title, due_date, priority, project_name):
super().__init__(title, due_date, priority)
self.project_name = project_name
def display_details(self):
print(f'Project: {self.project_name} - Task:
{self.title}, Due Date: {self.due_date}, Priority:
{self.priority}')
def sort_tasks(criteria):
if criteria == 'priority':
tasks.sort(key=lambda task: task.priority)
elif criteria == 'due_date':
tasks.sort(key=lambda task: task.due_date)
# Example usage
sort_tasks('priority')
120
def filter_by_project(project_name):
for task in tasks:
if isinstance(task, ProjectTask) and task.project_name ==
project_name:
task.show_task()
def save_tasks_to_file(filename='tasks.txt'):
with open(filename, 'w') as file:
for task in tasks:
if isinstance(task, ProjectTask):
file.write(f'project,{task.title},{task.due_date},{task.priority}
,{task.completed},{task.przoject_name}\n')
else:
file.write(f'task,{task.title},{task.due_date},{task.priority},{t
ask.completed}\n')
121
Solution:
This feature allows marking tasks as completed and filtering completed or incomplete tasks.
class Task:
def __init__(self, title, due_date, priority):
self.title = title
self.due_date = due_date
self.priority = priority
self.completed = False
def mark_complete(self):
self.completed = True
def show_task(self):
status = "Completed" if self.completed else "Incomplete"
print(f"Task: {self.title}, Due Date: {self.due_date},
Priority: {self.priority}, Status: {status}")
def show_completed_tasks(tasks):
for task in tasks:
if task.completed:
task.show_task()
def show_incomplete_tasks(tasks):
for task in tasks:
if not task.completed:
task.show_task()
2. Search Tasks by Title:
This feature allows users to update task titles, due dates, and priorities.
122
def update_task_details(tasks, task_num):
if 0 < task_num <= len(tasks):
task = tasks[task_num - 1]
new_title = input(f"Enter new title (or press Enter to
keep '{task.title}'): ") or task.title
new_due_date = input(f"Enter new due date (or press Enter
to keep '{task.due_date}'): ") or task.due_date
new_priority = input(f"Enter new priority (or press Enter
to keep '{task.priority}'): ") or task.priority
task.title = new_title
task.due_date = new_due_date
task.priority = new_priority
print("Task updated successfully.")
else:
print("Invalid task number.")
4. Implement Task Deletion:
Enhance the text-based interface with clear prompts and feedback for user actions.
def task_management_menu(tasks):
while True:
print("\nTask Management System:")
print("1. Add a new task")
print("2. View all tasks")
print("3. Search tasks by title")
print("4. Mark task as completed")
print("5. Show completed tasks")
print("6. Show incomplete tasks")
print("7. Update task details")
print("8. Delete a task")
print("9. Exit")
123
choice = input("Choose an option: ")
if choice == '1':
add_task(tasks)
elif choice == '2':
view_tasks(tasks)
elif choice == '3':
title = input("Enter task title to search: ")
search_task_by_title(tasks, title)
elif choice == '4':
task_num = int(input("Enter task number to mark as
completed: "))
tasks[task_num - 1].mark_complete()
elif choice == '5':
show_completed_tasks(tasks)
elif choice == '6':
show_incomplete_tasks(tasks)
elif choice == '7':
task_num = int(input("Enter task number to update:
"))
update_task_details(tasks, task_num)
elif choice == '8':
task_num = int(input("Enter task number to delete:
"))
delete_task(tasks, task_num)
elif choice == '9':
print("Exiting Task Management System.")
break
else:
print("Invalid choice, please try again.")
Putting it all together:
# Example of putting it all together:
tasks = []
def add_task(tasks):
title = input("Enter task title: ")
due_date = input("Enter task due date (YYYY-MM-DD): ")
priority = input("Enter task priority (Low, Medium, High): ")
task = Task(title, due_date, priority)
tasks.append(task)
def view_tasks(tasks):
124
if tasks:
for i, task in enumerate(tasks, 1):
print(f"Task {i}:")
task.show_task()
else:
print("No tasks available.")
Explanation:
1. Add Task Completion Feature: You can mark tasks as completed and display either
completed or incomplete tasks.
2. Search Tasks by Title: You can search tasks by their title, and the system will display
matching tasks.
3. Update Task Details: You can update a task’s title, due date, or priority.
5. Improved User Interface: A menu system provides clear options for managing tasks,
ensuring a smooth user experience.
This code builds a robust task management system with features for managing tasks
efficiently.
125
Lab Manual for Week 6: Introduction to
APIs – Day 1
Day 1: Introduction to APIs
Time: 3 Hours
Learning Outcomes:
- Understand what an API is and how it works.
- Make HTTP requests using Python's `requests` library.
- Work with JSON data returned by APIs.
- Fetch data from public APIs.
Tasks:
1. What is an API? (15 mins):
Write a short description of what an API is.
import requests
response = requests.get('https://api.github.com')
print(response.status_code)
4. Accessing the Response Content (15 mins):
Access and print the content returned by the API request.
print(response.content)
5. Accessing JSON Data (15 mins):
Convert the API response content to JSON and print it.
data = response.json()
print(data)
6. Fetching Specific Data from JSON (15 mins):
Extract specific information from the JSON response. (e.g., Extract the 'current_user_url'
from GitHub API response).
126
current_user_url = data['current_user_url']
print(current_user_url)
7. Handling HTTP Errors (15 mins):
Write code to handle HTTP errors gracefully using `try-except`.
try:
response = requests.get('https://api.github.com')
response.raise_for_status()
except requests.exceptions.HTTPError as err:
print(f'HTTP error occurred: {err}')
8. Using API Parameters (15 mins):
Make an API request with query parameters. (e.g., Search for a user on GitHub).
response = requests.get('https://api.github.com/search/users',
params={'q': 'octocat'})
data = response.json()
print(data['items'][0])
9. Using Headers in API Requests (15 mins):
Add headers to your API requests, such as User-Agent.
response =
requests.get('https://api.openweathermap.org/data/2.5/weather?q=L
ondon&appid=YOUR_API_KEY')
data = response.json()
print(data['weather'][0]['description'])
11. Parsing Complex JSON (15 mins):
Parse and display nested JSON data from the API response.
weather_description = data['weather'][0]['description']
print(f'The weather is {weather_description}')
12. Rate Limiting in APIs (15 mins):
Research and explain how rate limiting works in APIs. Implement a check for status codes
that indicate rate limiting.
127
response = requests.get('https://api.quotable.io/random')
quote = response.json()
print(quote['content'])
14. Using API Keys (15 mins):
Explain what API keys are, and use an API key in an authenticated API request.
def fetch_data(url):
response = requests.get(url)
return response.json()
Assignment Task:
Solution Code:
import requests
def fetch_weather(city):
api_key = 'YOUR_API_KEY'
url =
f'https://api.openweathermap.org/data/2.5/weather?q={city}&appid=
{api_key}&units=metric'
try:
response = requests.get(url)
response.raise_for_status()
data = response.json()
temperature = data['main']['temp']
weather_description = data['weather'][0]['description']
humidity = data['main']['humidity']
print(f'Temperature: {temperature}°C')
print(f'Weather: {weather_description}')
128
print(f'Humidity: {humidity}%')
except requests.exceptions.HTTPError as err:
print(f'HTTP error occurred: {err}')
except Exception as err:
print(f'An error occurred: {err}')
129
Lab Manual for Week 6: Introduction to
APIs – Day 2
Day 2: External Libraries and Packages
Time: 3 Hours
Learning Outcomes:
- Understand how to install and use external libraries in Python.
- Learn how to use `pip` to manage libraries.
- Utilize external libraries for different functionalities.
Tasks:
1. What are External Libraries? (15 mins):
Write a short description of what external libraries are and why they are useful in Python.
!pip list
import requests
print(requests.__version__)
import os
print(os.listdir())
130
Write a Python script that uses the `requests` library to make an HTTP GET request to a
public API.
import requests
response = requests.get('https://api.github.com')
print(response.status_code)
data = response.json()
print(data)
import schedule
import time
def job():
print('Task running...')
schedule.every(1).minutes.do(job)
while True:
schedule.run_pending()
time.sleep(1)
import numpy as np
arr = np.array([1, 2, 3, 4, 5])
print(arr)
import smtplib
131
Test Email\nThis is a test email.')
server.quit()
import pyautogui
pyautogui.hotkey('ctrl', 't') # Open a new tab in browser
13. Working with Dates and Time using `datetime` (15 mins):
Use the `datetime` library to print the current date and time.
Assignment Task:
● **Automate Sending an Email Using `smtplib`** (45 mins):
Write a Python program that:
Solution Code:
import smtplib
132
def send_email(subject, body, to_email):
smtp_server = 'smtp.gmail.com'
smtp_port = 587
email_user = '[email protected]'
email_password = 'yourpassword'
try:
server = smtplib.SMTP(smtp_server, smtp_port)
server.starttls()
server.login(email_user, email_password)
# Usage
send_email('Test Subject', 'This is the body of the test email.',
'[email protected]')
133
Lab Manual for Week 6: Introduction to
APIs – Day 3
Day 3: Integrating APIs into the Project
Time: 3 Hours
Learning Outcomes:
- Learn how to integrate external APIs into a Python project.
- Apply API data to enhance project functionality.
- Work with JSON data returned by APIs and manipulate it.
Tasks:
1. 1. Review Your To-Do List Project (15 mins):
- Write a short summary of how your current To-Do List project works.
import requests
response = requests.get('https://api.quotable.io/random')
print(response.status_code)
data = response.json()
print(data)
134
- Extract specific information from the JSON response. For example, extract a quote from a
quotes API.
quote = data['content']
print(f'Quote of the day: {quote}')
# Example integration
print(f'Today's quote: {quote}')
try:
response = requests.get('https://api.quotable.io/random')
response.raise_for_status()
except requests.exceptions.HTTPError as err:
print(f'HTTP error occurred: {err}')
response = requests.get('https://api.quotable.io/quotes',
params={'author': 'Einstein'})
data = response.json()
print(data)
api_key = 'YOUR_API_KEY'
response =
requests.get(f'https://api.example.com/data?apikey={api_key}')
import schedule
import time
schedule.every(10).minutes.do(fetch_quote)
while True:
135
schedule.run_pending()
time.sleep(1)
if 'content' in data:
print('Valid response')
else:
print('Invalid response')
def fetch_quote():
response = requests.get('https://api.quotable.io/random')
return response.json()
Assignment Task:
● **Integrate an API into the To-Do List Project** (45 mins):
Write a Python program that:
Solution Code:
import requests
136
response = requests.get('https://api.quotable.io/random')
response.raise_for_status()
data = response.json()
return data['content']
except requests.exceptions.RequestException as err:
print(f"Error fetching quote: {err}")
return "No quote available."
137
Lab Manual for Week 6: Introduction to
APIs – Day 4
Day 4: Project Enhancement with Libraries
Time: 3 Hours
Learning Outcomes:
- Understand how to enhance your project using external libraries.
- Learn how to schedule tasks using the `schedule` library.
- Use `datetime` to handle dates in tasks.
Tasks:
1. Install the `schedule` Library (15 mins):
Use `pip` to install the `schedule` library.
import schedule
import time
while True:
schedule.run_pending()
time.sleep(1)
print(datetime.now())
schedule.every().day.at('08:00').do(lambda: print('Good
morning!'))
138
5. Adding a Deadline to a Task (15 mins):
Use `datetime` to add a deadline to a task and print how many days remain until the
deadline.
def my_task():
print('This is my custom task')
schedule.every(5).minutes.do(my_task)
while True:
schedule.run_pending()
time.sleep(1)
# Example:
task_deadline = datetime(2024, 10, 25)
print(f'Task deadline: {task_deadline}')
def show_upcoming_tasks(tasks):
current_date = datetime.now()
for task in tasks:
if (task['deadline'] - current_date).days <= 7:
print(task)
139
11. Storing Scheduled Tasks in a File (15 mins):
Write a Python script that saves all scheduled tasks in a text file.
Assignment Task:
● **Schedule Task Reminders for Your To-Do List** (45 mins):
Write a Python program that:
1. Schedules a reminder to check the To-Do List every day at 9:00 AM.
2. Tracks task deadlines and notifies when a deadline is within the next 2 days.
Solution Code:
import schedule
140
import time
from datetime import datetime
141
Lab Manual for Week 6: Introduction to
APIs – Day 5
Day 5: Project Day – API Integration and Task Scheduling
Time: 3 Hours
Learning Outcomes:
- Apply the knowledge of APIs and task scheduling to enhance the To-Do List project.
- Integrate external APIs and automate tasks using the `schedule` library.
- Use `datetime` for managing task deadlines and reminders.
Mega Tasks:
1. Full API Integration into To-Do List (45 mins):
Integrate an external API (e.g., weather or motivational quotes) into your To-Do List project.
Display the fetched data every time the user views their tasks.
import requests
142
Use the `schedule` library to schedule a daily reminder for users to check their tasks.
import schedule
import time
schedule_file = 'schedule.txt'
def mark_task_completed(task):
task['completed'] = True
def show_completed_tasks(tasks):
for task in tasks:
if task['completed']:
print(f"Completed: {task['task']}")
143
mark_task_completed(tasks[0])
show_completed_tasks(tasks)
144
from datetime import datetime, timedelta
def show_upcoming_tasks(tasks):
current_date = datetime.now()
upcoming_tasks = [task for task in tasks if (task['deadline']
- current_date).days <= 7]
for task in upcoming_tasks:
print(f"Upcoming task: {task['task']} - Due in
{(task['deadline'] - current_date).days} days")
show_upcoming_tasks(tasks)
145
Lab Manual for Week 7: Advanced
Python Concepts – Day 1
Day 1: Advanced Functions and Recursion
Time: 3 Hours
Learning Outcomes:
- Understand higher-order functions and how to use functions as arguments.
- Learn about lambda functions and their applications.
- Understand recursion and how it can be applied to solve problems.
Tasks:
1. What are Higher-Order Functions? (15 mins):
Write a short description of what higher-order functions are in Python.
def square(n):
return n * n
numbers = [1, 2, 3, 4]
print(apply_function(numbers, square))
numbers = [1, 2, 3, 4]
print(apply_function(numbers, lambda n: n * n))
146
people = [('Alice', 25), ('Bob', 20), ('Charlie', 30)]
sorted_people = sorted(people, key=lambda person: person[1])
print(sorted_people)
def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n - 1)
print(factorial(5))
def countdown(n):
if n == 0:
print('Blast off!')
else:
print(n)
countdown(n - 1)
countdown(5)
def fibonacci(n):
if n <= 1:
return n
else:
return fibonacci(n - 1) + fibonacci(n - 2)
147
print(fibonacci(10))
numbers = [1, 2, 3, 4]
doubled = list(map(lambda n: n * 2, numbers))
print(doubled)
def make_multiplier(factor):
return lambda x: x * factor
double = make_multiplier(2)
print(double(5))
numbers = [1, 2, 3, 4, 5, 6]
filtered = list(filter(lambda n: n % 2 != 0, numbers))
print(filtered)
def iterative_factorial(n):
result = 1
for i in range(1, n + 1):
result *= i
return result
148
print(iterative_factorial(5))
Assignment Task:
● **Recursive Sum of a List** (45 mins):
Write a Python program that uses recursion to:
2. Ensure that the program can handle both empty and non-empty lists.
Solution Code:
def recursive_sum(lst):
if len(lst) == 0:
return 0
else:
return lst[0] + recursive_sum(lst[1:])
149
Lab Manual for Week 7: Advanced
Python Concepts – Day 2
Day 2: Introduction to Data Visualization
Time: 3 Hours
Learning Outcomes:
- Understand how to create charts using the `matplotlib` library.
- Learn to create line and bar charts.
- Customize charts by adding labels, titles, and legends.
- Apply data visualization to the To-Do List project.
Tasks:
1. Installing Matplotlib (15 mins):
Use `pip` to install the `matplotlib` library.
x = [1, 2, 3, 4, 5]
y = [10, 20, 25, 30, 35]
plt.plot(x, y)
plt.show()
150
3. Creating a Line Chart (15 mins):
Use `matplotlib` to create a line chart that represents the growth of task completion over
time.
x = ['Day 1', 'Day 2', 'Day 3', 'Day 4', 'Day 5']
y = [2, 5, 7, 9, 12]
plt.plot(x, y)
plt.xlabel('Days')
plt.ylabel('Tasks Completed')
plt.title('Task Completion Over Time')
plt.show()
plt.bar(x, y)
plt.xlabel('Days')
plt.ylabel('Tasks Completed')
plt.title('Task Completion by Day')
plt.show()
151
5. Adding Labels and Titles (15 mins):
Customize your chart by adding labels to the axes and a title to the chart.
plt.plot(x, y)
plt.xlabel('Days')
plt.ylabel('Tasks Completed')
plt.title('Customized Task Completion Chart')
plt.show()
152
7. Using Different Line Styles (15 mins):
Customize the appearance of your lines by changing their color, width, and style (e.g.,
dashed or dotted).
153
8. Creating a Pie Chart (15 mins):
Create a pie chart that shows the percentage of tasks completed versus tasks pending.
154
10. Saving a Chart to a File (15 mins):
Save a chart to a file (e.g., PNG or PDF format) using `savefig()`.
plt.plot(x, y)
plt.xlabel('Days')
plt.ylabel('Tasks Completed')
plt.title('Task Completion Over Time')
plt.savefig('task_completion_chart.png')
plt.show()
plt.plot(x, y)
plt.xlabel('Days')
plt.ylabel('Tasks Completed')
plt.title('Task Completion with Grid Lines')
plt.grid(True)
plt.show()
plt.figure(figsize=(10, 6))
plt.plot(x, y)
plt.xlabel('Days')
plt.ylabel('Tasks Completed')
155
plt.title('Task Completion with Custom Figure Size')
plt.show()
plt.plot(x, y)
plt.xlabel('Days')
plt.ylabel('Tasks Completed')
plt.title('Task Completion with Annotations')
plt.annotate('Highest Point', xy=('Day 5', 12), xytext=('Day 3',
15),
arrowprops=dict(facecolor='black', shrink=0.05))
plt.show()
4. Displaying Legends (15 mins):
156
tasks = ['Completed', 'Pending']
counts = [8, 2]
plt.bar(tasks, counts)
plt.xlabel('Task Status')
plt.ylabel('Number of Tasks')
plt.title('Task Completion Status')
plt.show()
Assignment Task:
● **Task Completion Visualization** (45 mins):
Write a Python program that uses `matplotlib` to:
2. Create a bar chart showing the number of tasks completed versus the number of tasks
pending.
Solution Code:
157
plt.ylabel('Tasks Completed')
plt.title('Task Completion Over Time')
plt.show()
158
Lab Manual for Week 7: Advanced
Python Concepts – Day 3
Day 3: Data Manipulation with Pandas
Time: 3 Hours
Learning Outcomes:
- Learn how to use the `pandas` library for data manipulation.
- Perform operations like sorting, filtering, and grouping using DataFrames.
- Read and write data from different file formats.
- Apply data analysis to enhance your To-Do List project.
Tasks:
1. Installing Pandas (15 mins):
Use `pip` to install the `pandas` library.
import pandas as pd
159
import pandas as pd
data = {
'Name': ['Alice', 'Bob', 'Charlie', 'David', 'Eva'],
'Age': [24, 27, 22, 32, 29],
'City': ['New York', 'Los Angeles', 'Chicago', 'Houston',
'Phoenix'],
'Salary': [50000, 60000, 55000, 62000, 58000]
}
df = pd.DataFrame(data)
print(df)
2b. Write code to calculate and add the bonus column to the DataFrame.
import pandas as pd
160
'Age': [24, 27, 22, 32, 29],
'City': ['New York', 'Los Angeles', 'Chicago', 'Houston',
'Phoenix'],
'Salary': [50000, 60000, 55000, 62000, 58000]
}
df = pd.DataFrame(data)
print("DataFrame:\n", df)
df = pd.read_csv('tasks.csv')
print(df.head())
4. Writing Data to CSV (15 mins):
161
df.to_csv('tasks_output.csv', index=False)
sorted_df = df.sort_values(by='Status')
print(sorted_df)
df['Priority'] = [1, 2, 3]
print(df)
df = df.drop('Priority', axis=1)
print(df)
grouped = df.groupby('Status').size()
print(grouped)
162
df = pd.read_excel('tasks.xlsx')
df.to_excel('tasks_output.xlsx', index=False)
print(df.describe())
df['Status'].value_counts().plot(kind='bar')
plt.xlabel('Task Status')
plt.ylabel('Number of Tasks')
163
plt.title('Task Status Count')
plt.show()
def mark_high_priority(priority):
return 'High' if priority > 1 else 'Low'
merged_df['Priority Label'] =
merged_df['Priority'].apply(mark_high_priority)
print(merged_df)
df_reset = merged_df.reset_index(drop=True)
print(df_reset)
high_priority_tasks.to_csv('high_priority_tasks.csv', index=False)
164
Assignment Task:
● **Task Data Analysis** (45 mins):
Write a Python program that uses `pandas` to:
Solution Code:
import pandas as pd
import matplotlib.pyplot as plt
165
Lab Manual for Week 7: Advanced
Python Concepts – Day 4
Day 4: Enhancing the To-Do List with Data Visualization
Time: 3 Hours
Learning Outcomes:
- Understand how to enhance the To-Do List project using data visualization.
- Learn to apply visualizations to represent task progress and status.
- Integrate `matplotlib` with your project to create insightful visualizations.
Tasks:
1. Importing Matplotlib for Visualization (15 mins):
- Start by importing `matplotlib.pyplot` to use for data visualization.
166
4. Line Chart for Task Completion Over Time (15 mins):
- Create a line chart to show task completion over time.
days = ['Day 1', 'Day 2', 'Day 3', 'Day 4', 'Day 5']
tasks_completed = [2, 5, 7, 9, 12]
plt.plot(days, tasks_completed)
plt.xlabel('Days')
plt.ylabel('Tasks Completed')
plt.title('Task Completion Over Time')
plt.show()
plt.plot(days, tasks_completed)
plt.xlabel('Days')
plt.ylabel('Tasks Completed')
plt.title('Customized Task Completion Chart')
plt.show()
167
completion_rate = [80, 20]
labels = ['Completed', 'Pending']
plt.bar(labels, completion_rate, color=['green', 'red'])
plt.xlabel('Status')
plt.ylabel('Percentage')
plt.title('Task Completion Rate')
plt.show()
tasks = ['Day 1', 'Day 2', 'Day 3', 'Day 4', 'Day 5']
completed = [2, 5, 7, 9, 12]
new_tasks = [3, 4, 6, 7, 9]
plt.plot(tasks, completed, label='Completed Tasks')
plt.plot(tasks, new_tasks, label='New Tasks')
plt.xlabel('Days')
plt.ylabel('Tasks')
plt.title('Task Progress with Legends')
plt.legend()
plt.show()
168
tasks = ['Task 1', 'Task 2', 'Task 3']
days_remaining = [3, 7, 1]
plt.barh(tasks, days_remaining, color='blue')
plt.xlabel('Days Remaining')
plt.title('Task Deadlines')
plt.show()
plt.plot(days, tasks_completed)
plt.xlabel('Days')
plt.ylabel('Tasks Completed')
plt.title('Task Completion with Annotations')
plt.annotate('Highest Completion', xy=('Day 5', 12), xytext=('Day
3', 10),
arrowprops=dict(facecolor='black', shrink=0.05))
plt.show()
plt.plot(days, tasks_completed)
169
plt.xlabel('Days')
plt.ylabel('Tasks Completed')
plt.title('Task Completion Over Time')
plt.savefig('task_completion_chart.png')
plt.show()
170
# First plot: Task completion
ax1.bar(['Completed', 'Pending'], [8, 2])
ax1.set_title('Task Completion')
plt.tight_layout()
plt.show()
14. Creating Line Charts for Multiple Data Sets (15 mins):
- Create a line chart to show task completion for multiple teams over time.
Assignment Task:
● **Task Completion Visualization** (45 mins):
171
Write a Python program that uses `matplotlib` to:
Solution Code:
172
Lab Manual for Week 7: Advanced
Python Concepts – Day 5
Day 5: Project Day – Data Visualization Enhancement
Time: 3 Hours
Learning Outcomes:
- Apply the knowledge of data visualization to enhance the To-Do List project.
- Implement various types of charts and visual representations for task data.
- Integrate all previous tasks to build a final project component.
Mega Tasks:
1. Visualizing Task Completion Over Time (45 mins):
Create a line chart that shows how many tasks have been completed each day of the week.
This should represent the progress made over time.
days = ['Day 1', 'Day 2', 'Day 3', 'Day 4', 'Day 5']
tasks_completed = [2, 5, 7, 9, 12]
plt.plot(days, tasks_completed)
plt.xlabel('Days')
plt.ylabel('Tasks Completed')
plt.title('Task Completion Over Time')
plt.show()
173
categories = ['Work', 'Personal', 'Shopping']
completion_rate = [80, 50, 60]
plt.bar(categories, completion_rate, color=['blue', 'green',
'orange'])
plt.xlabel('Categories')
plt.ylabel('Completion Rate (%)')
plt.title('Task Completion by Category')
plt.show()
days = ['Day 1', 'Day 2', 'Day 3', 'Day 4', 'Day 5']
tasks_completed = [2, 5, 7, 9, 12]
plt.plot(days, tasks_completed)
plt.xlabel('Days')
plt.ylabel('Tasks Completed')
plt.title('Task Completion Over Time')
plt.show()
174
Create a pie chart that displays the task priorities (High, Medium, Low) for the tasks in your
To-Do List.
175
Lab Manual for Week 8: Project
Finalization – Day 1
Day 1: Review of All Key Concepts
Time: 3 Hours
Learning Outcomes:
- Review the main Python concepts learned during the course.
- Refactor and optimize the codebase for the final project.
- Perform code clean-up and ensure the project is well-structured.
● In this task, you will focus on writing user-friendly Python code by following best
practices such as proper use of input prompts, clear and informative error
messages, and making code more readable and maintainable.
Instructions:
Write a Python program that asks the user to enter their name, age, and favorite color.
Ensure that the input prompts are clear and easy to understand.
Example:
176
Extend the previous program to handle errors in user input. For example, if the user
enters an invalid number for age, show a friendly error message and ask them to enter a
valid number.
Example:
while True:
try:
age = int(input("How old are you? Please enter a number:
"))
break # Exit the loop if the input is valid
except ValueError:
print("Oops! That doesn't seem to be a number. Please try
again.")
After collecting the user's details (name, age, and favorite color), print a message that
summarizes the information in a friendly and polite manner.
Task: Write code that provides positive feedback to the user, thanking them for their
input and acknowledging the data they have entered.
Example:
print(f"Thank you, {name}! It's great to know that you are {age}
years old and love the color {favorite_color}.")
Modify the code to validate the user’s input for both the age and favorite color fields:
177
Example:
while True:
try:
age = int(input("How old are you? Please enter a number:
"))
if age <= 0:
print("Age cannot be zero or negative. Please enter a
valid age.")
continue
break
except ValueError:
print("Oops! That doesn't seem to be a number. Please try
again.")
while True:
favorite_color = input("What's your favorite color? ")
if favorite_color.strip() == "":
print("You didn't enter anything! Please enter your
favorite color.")
else:
break
Make your code more readable by adding comments that explain what each part of the
code does. This makes it easier for others (and your future self) to understand.
Task: Add comments throughout your program to explain the purpose of each section.
Example:
178
break
except ValueError:
print("Oops! That doesn't seem to be a number. Please try
again.")
Break your code into smaller, reusable functions to improve readability and
maintainability. This is important for writing user-friendly code that can be reused or
updated more easily.
Task: Write a function to get the user’s name, age, and favorite color. Return the values
and print the final message using a separate function.
Example:
def get_user_info():
name = input("Please enter your name: ")
179
print("You didn't enter anything! Please enter your favorite
color.")
else:
break
Clear User Prompts: Ensure input prompts are user-friendly and easy to
understand.
Error Handling: Gracefully handle invalid input by providing helpful error
messages.
Input Validation: Validate user input to avoid errors and unexpected behavior.
Code Modularity: Break the code into reusable functions for better readability
and maintainability.
Comments: Use comments to explain the purpose of each section of the code.
This task will help you practice writing Python code that is user-friendly, easy to
understand, and maintainable. Let me know if you need further clarifications or help!
Tasks:
1. Reviewing Variables and Data Types (15 mins):
Write a brief explanation of different data types in Python and provide examples of each.
180
def check_number(num):
if num > 0:
return "Positive"
elif num < 0:
return "Negative"
else:
return "Zero"
print(check_number(5))
def factorial(n):
result = 1
for i in range(1, n+1):
result *= i
return result
print(factorial(5))
tasks = ['Task 1', 'Task 2', 'Task 3', 'Task 4', 'Task 5']
for task in tasks:
print(task)
181
task_list.append(task)
def display_tasks(task_list):
for task in task_list:
print(task)
tasks = []
add_task(tasks, 'Finish Project')
add_task(tasks, 'Read Book')
display_tasks(tasks)
task_details = {
'title': 'Finish Project',
'priority': 'High',
'status': 'Incomplete'
}
print(task_details)
class Task:
def __init__(self, title, priority, status):
self.title = title
self.priority = priority
self.status = status
def display(self):
print(f"Title: {self.title}, Priority: {self.priority},
Status: {self.status}")
182
def read_tasks_from_file(filename):
with open(filename, 'r') as file:
tasks = file.readlines()
for task in tasks:
print(task.strip())
read_tasks_from_file('tasks.txt')
def read_file_with_error_handling(filename):
try:
with open(filename, 'r') as file:
data = file.read()
print(data)
except FileNotFoundError:
print(f"File '{filename}' not found!")
read_file_with_error_handling('tasks.txt')
import math
print(math.sqrt(16))
def display_tasks(task_list):
for task in task_list:
183
print(task)
tasks = []
add_task(tasks, 'Finish Project')
display_tasks(tasks)
remove_task(tasks, 'Finish Project')
display_tasks(tasks)
def recursive_sum(lst):
if len(lst) == 0:
return 0
else:
return lst[0] + recursive_sum(lst[1:])
numbers = [1, 2, 3, 4, 5]
print(recursive_sum(numbers))
Assignment Task:
● **Project Refactoring Assignment** (45 mins):
Refactor your To-Do List project by doing the following:
1. Create separate functions for each major action (e.g., adding, removing, displaying tasks).
3. Ensure the code follows clean coding principles, including proper naming conventions,
comments, and error handling.
Solution Code:
184
if task in task_list:
task_list.remove(task)
def display_tasks(task_list):
for task in task_list:
print(task)
def main():
tasks = []
add_task(tasks, 'Finish Project')
display_tasks(tasks)
remove_task(tasks, 'Finish Project')
display_tasks(tasks)
if __name__ == "__main__":
main()
185
Lab Manual for Week 8: Project
Finalization – Day 2
Day 2: Final Project Adjustments
Time: 3 Hours
Learning Outcomes:
- Apply final touches to the To-Do List project.
- Test the project to ensure it functions as expected.
- Improve the user interface for better user experience.
Tasks:
1. Review of Project (15 mins):
Write a brief review of the current state of your To-Do List project. Identify areas where
improvements can be made.
tasks = []
task = input("Enter a task: ")
add_task(tasks, task)
186
remove_task(tasks, 'Complete Homework')
tasks = []
add_task(tasks, 'Finish Project', 'Work')
print(tasks)
tasks = []
add_task(tasks, 'Finish Project', 'Completed')
print(tasks)
187
def display_tasks_with_status(task_list):
for task in task_list:
print(f"Task: {task['task']} - Status: {task['status']}")
188
def mark_task_as_completed(task_list, task):
for t in task_list:
if t['task'] == task:
t['status'] = 'Completed'
print(f"Task '{task}' marked as completed!")
break
def sort_tasks_by_status(task_list):
completed = [task for task in task_list if task['status'] ==
'Completed']
pending = [task for task in task_list if task['status'] ==
'Pending']
print("Completed Tasks:", completed)
print("Pending Tasks:", pending)
189
print(tasks)
Assignment Task:
● **Final Adjustments Assignment** (45 mins):
Write a Python program that allows the following tasks:
Solution Code:
190
def mark_task_as_completed(task_list, task):
for t in task_list:
if t['task'] == task:
t['status'] = 'Completed'
print(f"Task '{task}' marked as completed!")
# Example usage:
tasks = []
add_task(tasks, 'Finish Project', 'Work')
edit_task(tasks, 'Finish Project', 'Complete Project')
search_task(tasks, 'complete')
mark_task_as_completed(tasks, 'Complete Project')
print(tasks)
191
Lab Manual for Week 8: Project
Finalization – Day 3
Day 3: Introduction to Git and Version Control
Time: 3 Hours
Learning Outcomes:
- Understand the importance of version control systems like Git.
- Learn basic Git commands and use them to manage your project.
- Collaborate on projects using GitHub and manage project updates with branches and
commits.
Tasks:
1. 1. What is Git? (15 mins):
- Write a brief explanation of what Git is and why it's important for version control.
git --version
cd path/to/your/project
git init
git status
git add .
192
git commit -m "Initial commit of To-Do List project"
git log
193
git checkout master
git merge new-feature
git rm new_script.py
git commit -m "Removed new_script.py"
git diff
194
- Clone an existing repository from GitHub to your local machine.
20. 20. Scenario: Using GitHub for Project Updates (15 mins):
- In this task, you will simulate a code update scenario. Follow these steps to demonstrate
how to update your project using GitHub:
- Create a branch for a new feature (e.g., adding task deadlines).
- Implement the feature and commit the changes.
- Push the branch to GitHub and open a pull request.
- Merge the pull request into the master branch.
- Pull the changes to your local machine.
- Test the updated project code.
# Step 4: Merge the pull request on GitHub, then pull the changes
locally
git checkout master
git pull origin master
Assignment Task:
● **Git and Version Control Assignment** (45 mins):
Perform the following tasks using Git and GitHub:
3. Create a new branch for a feature and merge it back into the master branch.
195
4. Push the changes to GitHub and test the updated code.
Solution Steps:
196
Lab Manual for Week 8: Project
Finalization – Day 4
Day 4: Project Deployment
Time: 3 Hours
Learning Outcomes:
- Learn how to deploy Python applications.
- Understand the basics of Python packaging and deployment platforms.
- Deploy a Python project using a platform like Heroku or similar services.
Tasks:
1. Introduction to Deployment (15 mins):
Write a brief explanation of what deployment is and why it's important for Python projects.
@app.route('/')
def home():
197
return 'Hello, World!'
if __name__ == '__main__':
app.run(debug=True)
python app.py
# Create a Procfile
echo "web: gunicorn app:app" > Procfile
heroku --version
heroku login
198
git add .
git commit -m "Initial deployment"
git push heroku master
heroku open
199
Assignment Task:
● **Deploy a Python Project** (45 mins):
Follow these steps to deploy your To-Do List project on Heroku:
2. Prepare the project for deployment by adding a `Procfile` and necessary dependencies.
Solution Steps:
app = Flask(__name__)
@app.route('/')
def home():
return 'This is the To-Do List project!'
if __name__ == '__main__':
app.run(debug=True)
200
Lab Manual for Week 8: Project
Finalization – Day 5
Day 5: Final Project Presentation and Assessment
Time: 3 Hours
Learning Outcomes:
- Review the final To-Do List project and make any last adjustments.
- Present the final project, explaining the process, features, and challenges.
- Perform a self-assessment of the project and receive feedback from peers or instructors.
# Adding a task
add_task(tasks, 'Complete the project')
# Viewing tasks
view_tasks(tasks)
# Deleting a task
delete_task(tasks, 'Complete the project')
201
def add_task(task_list, task):
if task and task not in task_list:
task_list.append(task)
print(f"Task '{task}' added successfully! You have
{len(task_list)} tasks in total.")
git add .
git commit -m "Final deployment of To-Do List project"
git push heroku master
202
- Example: Reflect on the project. Write a brief paragraph about what you learned and how
you overcame challenges. Here’s an example:
I learned how to manage a project using Git and GitHub. The biggest challenge I faced was
deploying the app, but I resolved it by following Heroku’s documentation.
203
- task_list: list of tasks
- task: the task to be deleted
'''
if task in task_list:
task_list.remove(task)
print(f"Task '{task}' deleted.")
else:
print(f"Task '{task}' not found.")
git add .
git commit -m "Final version"
git push origin master
During this course, I learned how to break down a project into smaller tasks and manage
them using Git. I also gained hands-on experience with deployment using Heroku.
204
- Example: Write down ideas for future improvements or new projects you’d like to work
on. For example, you could expand the To-Do List project to include deadlines or
notifications.
The End
205