0% found this document useful (0 votes)
15 views17 pages

Python Programming Assignments Guide

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

Python Programming Assignments Guide

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

PYTHON ASSIGNMENT BANK

Day-2
Assignment 1: Area of a Circle Write a program that calculates the area of a circle given its
radius. The formula for the area of a circle is: Area = π * radius^2.

Take radius from user. Use π as 3.14

Assignment 2: Temperature Conversion Write a program that converts temperature in


Fahrenheit to Celsius. The formula is: Celsius = (Fahrenheit - 32) * 5/9.

Take Fahrenheit from user.

Assignment 3: Variable Swap Write a program that takes two integer inputs from the user and
swaps their values without using a temporary variable.

Assignment 4: Simple Interest Calculator Write a program that calculates the simple interest
for a given principal amount, rate of interest, and time period. The formula for simple interest is:
Simple Interest = (principal * rate * time) / 100.

Take principal ,rate , time from user.


Assignment 5: String Reversal Write a program that takes a string as input and prints its
reverse.

Example - user gave “Rajdeep”, your output will be “peedjaR”

Assignment 6: User Information Write a program that takes the user's name, age, and
favorite color as inputs and then prints them in a formatted message.

Assignment 7: Odd or Even Checker Write a program that takes an integer input from the
user and determines whether it's odd or even.

Assignment 8: Shopping Cart Total Write a program that simulates a shopping cart. Prompt
the user to enter the prices of items they want to buy. After they're done, calculate and print the
total cost of all the items in the cart.

Assignment 9 Character Count Write a program that takes a string as input and counts the
number of occurrences of a specific character entered by the user.

Assignment 10: Name Initials Write a program that takes a full name as input and outputs the
initials in uppercase. For example, if the input is "John Doe", the output should be "JD".

Day-3
Assignment 11:String Manipulation Basics Create a Python program that takes a user's full
name as input and prints it in reverse order (last name, first name).
●​ Then, count and display the total number of characters in the full name.
●​ Finally, extract and display the initials of the first and last names.

Assignment 12:String Searching and Replacing:


●​ Given a text containing a sample paragraph of text.
●​ Write a Python program that reads this paragraph and searches for a “specific word” and
display the number of occurrence of that word.
●​ Replace all occurrences of the word with “replace with” word and display the modified
text.

Given Paragraph: Python is commonly used for developing websites and software, task
automation, data analysis, and data visualization. Since it's relatively easy to learn, Python has
been adopted by many non-programmers such as accountants and scientists, for a variety of
everyday tasks, like organizing finances
Specific word: Python

Replace with : PYTHON

Assignment 13: Palindrome Checker:


●​ Create a Python function that checks if a given string is a palindrome (reads the same
forwards and backwards).
●​ Prompt the user for a string and use the function to determine if it's a palindrome.
●​ Display an appropriate message indicating whether the input is a palindrome or not.

Assignment 14:String Formatting and Validation:


●​ Design a program that validates email addresses entered by users.
●​ Prompt the user for an email address and check if it follows the standard email format
(e.g., contains "@" and ".").
●​ Display a message indicating whether the email is valid or not.

Valid email format: your_name.surname@[Link]

Assignment 15:Text Analysis and Statistics:

●​ Provide a text containing a lengthy article or essay.


●​ Create a Python program that reads this file and calculates the following statistics:
○​ Total word count
○​ Total sentence count
○​ Average word length

Paragraph to analyze:
The metaverse is an emerging digital realm that is captivating imaginations worldwide. In
essence, it represents a collective virtual universe where individuals can interact, socialize,
work, and play within a vast interconnected space. Imagine a sprawling digital landscape, akin
to a science fiction dream, where people utilize avatars to navigate this immersive environment.
Within the metaverse, possibilities are seemingly limitless, encompassing everything from virtual
reality gaming and educational experiences to social gatherings and commerce.

Key technologies driving the metaverse include augmented reality (AR), virtual reality (VR),
blockchain, and advanced artificial intelligence (AI). Companies like Facebook's Meta, Roblox,
and Fortnite's Epic Games are already investing heavily in metaverse development, envisioning
a future where it becomes an integral part of our daily lives. The metaverse's potential extends
far beyond entertainment; it could revolutionize remote work, education, and even healthcare,
offering new ways to connect and collaborate across distances.

Day-4
Assignment 16: Create a Python program that takes two numbers as input from the user and
performs basic arithmetic operations (addition, subtraction, multiplication, division, and modulus)
on them. Display the results.

Assignment 17: Write a program that asks the user to input two numbers and then compares
them using comparison operators (>, <, ==, !=) to determine if the first number is greater than,
less than, equal to, or not equal to the second number. Display the results using Boolean values
(True/False).

Assignment 18: Build a program that simulates a simple access control system. Prompt the
user for a username and password. Then, use logical operators (and, or, not) to determine
whether the user should be granted access or denied access based on predefined username
and password criteria. Provide appropriate feedback to the user.

Assignment 19: List Manipulation: Write a Python program that does the following:

●​ Initializes an empty list.


●​ Asks the user to enter a series of numbers (use a loop for this).
●​ Appends each entered number to the list.
●​ After the user is done entering numbers, display the list.

Assignment 20 : List Comprehension and Filtering: Create a Python program that performs
the following tasks:

●​ Initialize a list of numbers.


●​ Use list comprehension to create a new list that contains only the even numbers from the
original list.
●​ Use another list comprehension to create a new list that contains squares of the
numbers from the original list.
●​ Ask the user to input a number and use list comprehension to create a new list that
contains only the numbers from the original list that are greater than the user's input.
●​ Display all three lists.

Day-5
Assignment 21: Tuple Operations Create a Python program that performs the following tasks:

1.​ Define two tuples, tuple1 and tuple2, containing at least five elements each.
2.​ Write a function that takes these two tuples as input and returns a new tuple,
combined_tuple, which contains elements from both tuple1 and tuple2.
3.​ Write a function to calculate the sum of all elements in combined_tuple.
4.​ Write a function to find the maximum and minimum values in combined_tuple.
5.​ Print the combined_tuple, sum of elements, maximum, and minimum values.
Assignment 22: Tuple Unpacking Create a Python program that focuses on tuple unpacking:

1.​ Define a tuple named student containing information about a student (e.g., name, age,
grade, school).
2.​ Use tuple unpacking to extract and assign the values from the student tuple to
individual variables.
3.​ Write a function that takes the individual variables as arguments and prints out a
formatted string with the student's information (e.g., "Name: John, Age: 18, Grade: A,
School: XYZ High School").
4.​ Test your program with different student information tuples.

Assignment 23: Tuple Slicing and Manipulation Design a Python program that explores tuple
slicing and manipulation:

1.​ Create a tuple named original_tuple containing a sequence of at least 10 elements


(e.g., numbers, strings, or a mix of both).
2.​ Write a function that slices the original_tuple to extract a subset of elements (e.g.,
elements at even indices).
3.​ Implement a function that replaces specific elements in the sliced tuple with new values.
4.​ Create a new tuple, modified_tuple, by combining the modified slice with the
remaining elements of the original_tuple.
5.​ Write a function to count the occurrences of a specific element within the
modified_tuple.
6.​ Print the modified_tuple, the count of the specific element, and the original
original_tuple.

Assignment 24: Set Operations Create a Python program that focuses on set operations:

1.​ Define two sets, set1 and set2, with a variety of elements (numbers, strings, or a mix
of both).
2.​ Write a function that finds and prints the union of set1 and set2.
3.​ Implement a function to find and print the intersection of set1 and set2.
4.​ Write a function that determines and prints the elements that are unique to set1 (i.e.,
elements that are not in set2).
5.​ Create a new set, set3, containing elements that are present in either set1 or set2,
but not both.
6.​ Write a function to check if set1 is a subset of set2 and print the result.
7.​ Print the results of each operation and the final contents of set3.

Assignment 25: Set Manipulation and Filtering Design a Python program that explores set
manipulation and filtering:
1.​ Create a set named original_set containing at least 15 elements (numbers, strings,
or a mix of both).
2.​ Write a function that removes duplicates from original_set and stores the result in a
new set, unique_set.
3.​ Implement a function that filters unique_set to include only elements that meet a
specific condition (e.g., selecting only even numbers or strings starting with a vowel).
4.​ Write a function that calculates and prints the sum of all numeric elements in the filtered
set.
5.​ Create a set, filtered_set2, by applying a different filter condition (e.g., selecting
elements containing a specific substring).
6.​ Write a function to find and print the intersection of filtered_set and
filtered_set2.
7.​ Print the contents of filtered_set, filtered_set2, and the intersection.

Day-6
Assignment 26: Basic Dictionary Operations

Description: In this assignment, you'll practice basic dictionary operations.

1.​ Create an empty dictionary called student_scores.


2.​ Add the following student scores to the dictionary:
○​ "Alice" scored 95
○​ "Bob" scored 88
○​ "Charlie" scored 92
○​ "David" scored 78
3.​ Print the scores of all students in the dictionary.
4.​ Calculate and print the average score of the students.
5.​ Add a new student, "Eve," with a score of 87.
6.​ Print the updated scores of all students.

Assignment 27: Dictionary Manipulation

Description: In this assignment, you'll perform more advanced dictionary operations.

1.​ Create a dictionary called inventory with the following items and their respective
quantities:
○​ "apples": 50
○​ "bananas": 75
○​ "oranges": 100
○​ "grapes": 30
2.​ Write a function update_inventory(item, quantity) that takes an item and a
quantity as arguments and updates the inventory accordingly. If the item already exists,
add the quantity to the existing quantity. If the item doesn't exist, add it to the inventory.
3.​ Test your update_inventory function by adding 20 more apples, 10 more bananas,
and 15 pineapples to the inventory.
4.​ Write a function print_inventory() that prints the current inventory in a user-friendly
format (e.g., "Item: Quantity").
5.​ Use the print_inventory function to display the updated inventory.

Assignment 28: Dictionary Comprehensions

Description: In this advanced assignment, you'll explore dictionary comprehensions.

1.​ Create two lists:


○​ names containing the names of students: ["Alice", "Bob", "Charlie", "David",
"Eve"]
○​ scores containing the corresponding scores: [95, 88, 92, 78, 87]
2.​ Use a dictionary comprehension to create a dictionary called student_scores that
maps names to scores.
3.​ Write a function filter_scores(min_score) that takes a minimum score as an
argument and returns a new dictionary containing only the students who scored equal to
or above the minimum score.
4.​ Test the filter_scores function with a minimum score of 90 and print the resulting
dictionary.
5.​ Write a function calculate_average_score() that calculates and returns the
average score of all students in the student_scores dictionary.
6.​ Use the calculate_average_score function to display the average score.

Assignment 29: Grading System

Description: In this assignment, you'll create a simple grading system based on students'
scores.

1.​ Write a Python program that takes a student's score as input.


2.​ Using if-elif-else statements, assign a letter grade to the student based on the
following criteria:
○​ Score >= 90: "A"
○​ Score >= 80 and < 90: "B"
○​ Score >= 70 and < 80: "C"
○​ Score >= 60 and < 70: "D"
○​ Score < 60: "F"
3.​ Print the student's score and corresponding letter grade.
Assignment 30: Calculator Application

Description: In this assignment, you'll create a simple calculator application that can perform
basic arithmetic operations.

1.​ Write a Python program that takes two numbers and an arithmetic operator as input from
the user. The possible operators are "+", "-", "*", and "/".
2.​ Use if-elif-else statements to perform the selected operation on the two numbers
and display the result.
3.​ Ensure that the program handles division by zero gracefully. If the user attempts to
divide by zero, display an error message instead of crashing.
4.​ Implement error handling for invalid input. If the user enters an invalid operator (anything
other than "+", "-", "*", or "/"), display an error message.
5.​ Allow the user to continue performing calculations or exit the program after each
calculation.
6.​ Add a loop to keep the calculator running until the user chooses to exit.

Day-7
Do the below programs using While loop

Assignment 31: Basic While Loop

Write a Python program that uses a while loop to print numbers from 1 to 10.

Assignment 32: Sum of Even Numbers

Write a Python program that calculates and prints the sum of all even numbers from 1 to 50
using a while loop.

Assignment 33: Guess the Number Game

Create a number guessing game in Python. The computer selects a random number between 1
and 100, and the user has to guess the number. Use a while loop to keep the game running
until the user guesses the correct number.

Assignment 34: Factorial Calculation

Write a Python program that calculates and prints the factorial of a given number using a while
loop. Ensure the program handles non-negative integer input.

Assignment 35: Palindrome Checker


Create a Python program that checks if a given word is a palindrome (reads the same forwards
and backwards). Use a while loop to compare characters from the start and end of the word.
The program should print whether the word is a palindrome or not.

Do the below program using For loop

Assignment 36: Basic For Loop

Write a Python program that uses a for loop to print numbers from 1 to 10.

Assignment 37: Sum of Even Numbers

Write a Python program that calculates and prints the sum of all even numbers from 1 to 50
using a for loop.

Assignment 38: Multiplication Table

Create a Python program that generates and prints the multiplication table for a given number.
Use a for loop to iterate from 1 to 10 to generate the table for that number.

Assignment 39: Prime Number Checker

Write a Python program that checks if a given number is prime. Use a for loop to test if the
number is divisible by any integer from 2 to the square root of the number. Print whether the
number is prime or not.

Assignment 40: Fibonacci Sequence

Create a Python program that generates and prints the first n terms of the Fibonacci sequence
using a for loop. The Fibonacci sequence starts with 0 and 1, and each subsequent term is the
sum of the two previous terms.

Day-8
Assignment 41- Basic Function Definition: Write a Python function called calculate_average

that takes a list of numbers as input and returns their average. Test the function with a sample
list of numbers.

Assignment 42 - Function with Multiple Parameters: Create a function find_largest that accepts
three numbers as parameters and returns the largest among them. Write a program that takes
user input for three numbers and then calls the find_largest function to display the result.
Assignment 43 -Function with Default Arguments: Define a function power_of that takes two
arguments, base and exponent, with a default value of 2 for exponent. The function should
return the result of raising the base to the given exponent. Test the function by calculating the
squares and cubes of various numbers.

Day-9
Assignment 44: Basic Lambda Function

Objective: Create a simple lambda function to perform a basic mathematical operation.

1.​ Write a lambda function that takes two parameters x and y and returns their sum.
2.​ Use this lambda function to calculate the sum of two numbers, e.g., 3 and 5.
3.​ Print the result.

Assignment 45: Filtering with Lambda

Objective: Practice using lambda functions for filtering a list.

1.​ Create a list of integers containing both even and odd numbers, e.g., [1, 2, 3, 4,
5, 6, 7, 8, 9, 10].
2.​ Use a lambda function and the filter() function to filter the even numbers from the
list.
3.​ Print the filtered list of even numbers.

Assignment 46: Sorting with Lambda

Objective: Explore lambda functions in sorting.

1.​ Create a list of dictionaries, where each dictionary represents a person with keys 'name'
and 'age'. For example:

people = [{'name': 'Alice', 'age': 30},

​ {'name': 'Bob', 'age': 25},

​ {'name': 'Charlie', 'age': 35},

​ {'name': 'David', 'age': 28}]


2.​ Use the sorted() function with a lambda function as the key parameter to sort the list
of dictionaries by age in ascending order.
3.​ Print the sorted list of dictionaries.

Day-10
Assignment 47: Basic Class Creation

○​ Create a Python class named Student with attributes such as name, age, and
grade.
○​ Implement a method in the class to display the student's information.
○​ Create instances of the class and demonstrate how to use them.

Assignment 48: Inheritance

○​ Define a base class called Shape with attributes color and area.
○​ Create two derived classes, Circle and Rectangle, that inherit from Shape.
○​ Implement methods to calculate the area of each shape and display their
properties.
○​ Demonstrate the use of inheritance by creating instances of both derived classes.

Assignment 49: Encapsulation and Getter/Setter Methods

○​ Create a class called BankAccount with private attributes balance and


account_holder.
○​ Implement getter and setter methods to access and modify the balance.
○​ Include methods for deposit and withdrawal, ensuring that the balance is updated
correctly.
○​ Demonstrate the use of the class by creating instances and performing
transactions.

Assignment 50: Class Methods and Static Methods

○​ Create a class called MathOperations with class methods for basic


mathematical operations like addition, subtraction, multiplication, and division.
○​ Implement a static method to compute the square root of a number.
○​ Demonstrate the use of both class methods and the static method in your code.

Assignment 51 :Composition

○​ Create two classes: Author and Book.


○​ The Author class should have attributes such as name, birth_date, and
nationality.
○​ The Book class should have attributes like title, publication_date, and an
instance of the Author class.
○​ Demonstrate composition by creating instances of the Book class with
associated Author instances.

Day-11
Assignment 52 :Basic Inheritance

○​ Create a base class named Vehicle with attributes like make, model, and
year.
○​ Implement a method in the Vehicle class to display the vehicle
information.
○​ Create two derived classes, Car and Motorcycle, that inherit from
Vehicle.
○​ Add unique attributes and methods to each derived class.
○​ Demonstrate the use of inheritance by creating instances of both derived
classes.

Assignment 53 : Method Overriding

○​ Extend the previous assignment by overriding the display method in the


Car class.
○​ Customize the display method in the Car class to include additional
information specific to cars, such as the number of doors.
○​ Demonstrate that the overridden method is called when displaying
information about a car instance.

Assignment 54 : Multilevel Inheritance

○​ Create a base class named Animal with attributes like name and sound.
○​ Extend the Animal class to create a derived class named Mammal with
additional attributes and methods.
○​ Further extend the hierarchy by creating a class named Dog that inherits
from Mammal.
○​ Demonstrate the use of multilevel inheritance by creating instances of the
Dog class.

Assignment 55 : Abstract Base Class


○​ Define an abstract base class named Shape with an abstract method for
calculating the area.
○​ Create two classes, Circle and Rectangle, that inherit from the Shape
class.
○​ Implement the area calculation method in each derived class.
○​ Demonstrate the use of the abstract base class by creating instances of
both derived classes.

Assignment 56 : Polymorphism

○​ Create a base class named Employee with attributes like name and salary.
○​ Extend the Employee class to create two derived classes, Manager and
Developer.
○​ Implement a method in each class to calculate the bonus.
○​ Demonstrate polymorphism by calling the bonus calculation method on
instances of both Manager and Developer classes.

Day-12
Assignment 57 :Basic Polymorphism

○​ Create a base class named Animal with a method make_sound.


○​ Create two derived classes, Dog and Cat, that inherit from Animal.
○​ Implement the make_sound method in each derived class to produce
different sounds.
○​ Demonstrate polymorphism by calling the make_sound method on
instances of both Dog and Cat.

Assignment 58 :Operator Overloading

○​ Define a class called Vector that represents a 2D vector.


○​ Implement the __add__ method to allow adding two vectors using the +
operator.
○​ Implement the __mul__ method to allow multiplying a vector by a scalar
using the * operator.
○​ Demonstrate the use of operator overloading by performing vector addition
and scalar multiplication.

Assignment 59 :Duck Typing


○​ Create three classes: Circle, Rectangle, and Triangle, each
representing a geometric shape.
○​ Implement a method named area in each class to calculate the area of the
respective shape.
○​ Demonstrate duck typing by creating a function that takes an object and
calls its area method without checking its type.

Assignment 60 :Function Polymorphism

○​ Create a function named calculate_area that takes an object


representing a shape and calculates its area.
○​ Ensure that the function works with different shapes (e.g., circles,
rectangles) by relying on polymorphism.
○​ Demonstrate the function with instances of various shape classes.

Assignment 61 :Abstract Base Class and Polymorphism

○​ Define an abstract base class named Shape with an abstract method


calculate_area.
○​ Create two classes, Circle and Rectangle, that inherit from the Shape
class.
○​ Implement the calculate_area method in each derived class.
○​ Demonstrate polymorphism by creating instances of both Circle and
Rectangle and calling the calculate_area method.

Day-13
Assignment 62 :Understanding Local Scope

○​ Write a Python function that declares a variable inside the function (local
scope).
○​ Attempt to access the variable outside the function and observe the
results.
○​ Explain the concept of local scope and how it affects variable access.

Assignment 63 :Global Scope

○​ Create a global variable outside of any function.


○​ Write a function that attempts to modify the global variable.
○​ Demonstrate the difference between accessing a global variable and
creating a new local variable with the same name inside a function.

Assignment 64 :Encapsulation and Local Scope

○​ Define a class called Counter with an instance variable count.


○​ Implement methods to increment and retrieve the count value.
○​ Demonstrate how encapsulation works to protect the variable count from
being directly accessed or modified outside the class.

Assignment 65 :Nested Functions and Scope

○​ Write a function that declares a variable in the outer function.


○​ Define an inner function within the outer function that attempts to access
the outer variable.
○​ Demonstrate how the inner function can access and modify variables from
the outer function's scope.

Assignment 66 :Nonlocal Keyword

○​ Create a function that declares a variable in the local scope.


○​ Define an inner function within the first function and use the nonlocal
keyword to modify the outer function's variable.
○​ Demonstrate the use of nonlocal and explain how it differs from global.

Day-14
Assignment 67: Basic Module Creation

Task: Create a Python module named math_operations that includes functions for
basic mathematical operations such as addition, subtraction, multiplication, and division.
Import this module into a separate script and use its functions to perform arithmetic
operations.

Assignment 68: Data Processing Module

Task: Develop a Python module named data_processor that contains functions for
common data processing tasks, such as sorting a list, finding the average of a list of
numbers, and checking if a number is prime. Implement a script to demonstrate the
usage of these functions.
Assignment 69: File Handling Module

Task: Build a module named file_handler that includes functions for reading from and
writing to text files. Create functions for reading the contents of a file, writing new data to
a file, and appending data to an existing file. Test these functions by reading and writing
to a sample text file.

Assignment 70: Object-Oriented Module

Task: Develop a Python module named student_module that defines a Student class
with attributes like name, age, and grades. Include methods for calculating the average
grade and displaying student information. Import and use this module in a script to
create instances of the Student class and perform operations on them.

Day-15
Assignment 71: Basic Error Handling

Task: Create a Python script that reads two numbers from the user and performs
division. Implement a try-except block to handle the ZeroDivisionError if the user
attempts to divide by zero. Provide a meaningful error message.

Assignment 72: File Reading with Error Handling

Task: Develop a script that reads data from a user-specified text file. Implement a
try-except block to handle the FileNotFoundError if the specified file does not exist.
Display an appropriate message in such cases.

Assignment 73: Custom Exception Handling

Task: Build a Python script that prompts the user for their age. Use a custom exception
class, say InvalidAgeError, to raise an exception if the entered age is less than 0 or
greater than 150. Implement a try-except block to catch and handle this custom
exception.

Assignment 74: API Request with Retry

Task: Create a script that makes an API request to a user-provided endpoint using the
requests library. Implement a try-except block to handle possible connection errors
([Link]). Allow the user to retry the request a
specified number of times before giving up.

You might also like