Lab-manual-Advanced Python Programming 4321602
Lab-manual-Advanced Python Programming 4321602
Laboratory Manual
Year: 2023-2024
Prepared By:
1
Index
2
Experiment No: 1 Date: / /
Objective:
String Operations Section Objectives:
1. Length Display:
a. Display the length of the input string.
2. Uppercase Display:
a. Display the input string in uppercase.
3. Lowercase Display:
a. Display the input string in lowercase.
4. First 5 Characters Display:
a. Display the first 5 characters of the input string.
5. Last 5 Characters Display:
a. Display the last 5 characters of the input string.
6. Reversed String Display:
a. Display the reversed version of the input string.
Solution:
# Function to demonstrate string operations
def string_operations(input_string):
# String operations
print("Original String:", input_string)
print("Length of the String:", len(input_string))
print("Uppercase:", input_string.upper())
print("Lowercase:", input_string.lower())
print("First 5 characters:", input_string[:5])
print("Last 5 characters:", input_string[-5:])
3
print("Reversed String:", input_string[::-1])
Output :
4
List Operations Section:
Original List: ['h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd']
List after appending '!': ['h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd', '!']
List after removing spaces: ['h', 'e', 'l', 'l', 'o', 'w', 'o', 'r', 'l', 'd', '!']
Reversed List: ['!', 'd', 'l', 'r', 'o', 'w', 'o', 'l', 'l', 'e', 'h']
Index of 'a': 9
Count of 'a': 0
Exercise:
1. Write a program to create, concatenate and print a string and accessing sub-string from a
given string.
2. Create a string variable with the text "Python Programming" and display its length.
3. Sort the numbers list in descending order and remove the last element.
EVALUATION:
Signature: _______________________
Date : _______________________
5
Experiment No: 2 Date: / /
Aim: Write a Python program showcasing built-in functions for Set manipulation.
Objective:
Output:
Enter elements for Set 1 (comma-separated): 1, 2, 3, 4
Enter elements for Set 2 (comma-separated): 3, 4, 5, 6
Set 1: {'3', '2', '1', '4'}
Set 2: {'3', '5', '6', '4'}
Union of Set 1 and Set 2: {'3', '2', '1', '5', '6', '4'}
Intersection of Set 1 and Set 2: {'3', '4'}
Difference (Set 1 - Set 2): {'2', '1'}
Difference (Set 2 - Set 1): {'5', '6'}
Symmetric Difference: {'2', '1', '5', '6'}
Is Set 1 a subset of Set 2: False
6
Is Set 2 a subset of Set 1: False
Are Set 1 and Set 2 disjoint: False
Exercise
EVALUATION:
Signature: _______________________
Date : _______________________
7
Experiment No: 3 Date: / /
Objective:
Solution :
8
Output:
Exercise:
1. Write a program to demonstrate tuples functions and operations
2. Write a program to input n numbers from the user and store these numbers in a tuple. Print
the maximum and minimum number from this tuple.
3. Write a program to input names of n employees and store them in a tuple. Also, input a
name from the user and find if this employee is present in the tuple or not.
EVALUATION:
Signature: _______________________
Date : _______________________
9
Experiment No: 4 Date: / /
Objective:
1. Accept two dictionaries from the user.
2. Merge the two dictionaries and display the result.
3. Display the keys, values, and items of each dictionary.
4. Check if a specific key is present in each dictionary.
5. Update the value of a specific key in each dictionary.
6. Remove a key-value pair from each dictionary.
7. Check if the dictionaries are equal.
10
dictionary_manipulation(dict1, dict2)
Output :
Enter Dictionary 1 (in the form of key-value pairs): {'a': 1, 'b': 2, 'c': 3}
Enter Dictionary 2 (in the form of key-value pairs): {'c': 4, 'd': 5, 'e': 6}
Exercise:
1. Create a dictionary named student_scores where keys are student names and values are
their scores, e.g., {"Alice": 88, "Bob": 76, "Charlie": 90}.
2. Update Bob's score to 82 and add a new student, "Diana", with a score of 95.
3. Write a program to concatenate the following dictionaries to create a new one. Sample
Dictionary: dic1={1:10, 2:20} dic2={3:30, 4:40} dic3={5:50,6:60} Expected Result: {1:
10, 2: 20, 3: 30, 4: 40, 5: 50, 6: 60}
EVALUATION:
Signature: _______________________
Date : _______________________
11
Experiment No: 5 Date: / /
Aim: Write a Python program that involves creating and importing a module.
Objective:
# math_operations.py
def add(x, y):
return x + y
def subtract(x, y):
return x - y
def multiply(x, y):
return x * y
def divide(x, y):
if y == 0:
return "Cannot divide by zero"
return x / y
# main_program.py
import math_operations
# Accepting two numbers from the user
num1 = float(input("Enter the first number: "))
num2 = float(input("Enter the second number: "))
print("\nResults:")
print("Addition:", result_addition)
print("Subtraction:", result_subtraction)
12
print("Multiplication:", result_multiplication)
print("Division:", result_division)
Output :
Enter the first number: 10
Enter the second number: 5
Results:
Addition: 15.0
Subtraction: 5.0
Multiplication: 50.0
Division: 2.0
Exercise:
1. Define module.
2. Write a program to define a module to find the area and circumference of a circle.
a) import the module to another program.
b) import a specific function from a module to another program.
EVALUATION:
Signature: _______________________
Date : _______________________
13
Experiment No: 6 Date: / /
Objective:
1. Create a Python package named shapes with modules circle and rectangle.
2. In the circle module, define functions to calculate the area and circumference of a circle.
3. In the rectangle module, define functions to calculate the area and perimeter of a
rectangle.
4. Import the shapes package in a main program.
5. Accept user input for choosing a shape (circle or rectangle) and relevant parameters.
6. Use functions from the imported package to calculate and display the area and
perimeter/circumference based on the chosen shape.
Directory Structure:
shapes/ # Package
|-- __init__.py # Initialization file for the package
|-- circle.py # Module for circle calculations
|-- rectangle.py # Module for rectangle calculations
main_program.py # Main program
circle.py (Module):
# circle.py
import math
def calculate_area(radius):
return math.pi * radius**2
def calculate_circumference(radius):
return 2 * math.pi * radius
rectangle.py (Module):
# rectangle.py
def calculate_area(length, width):
return length * width
def calculate_perimeter(length, width):
return 2 * (length + width)
# main_program.py
from shapes import circle, rectangle
# Accepting user input
shape_choice = input("Choose a shape (circle or rectangle): ").lower()
# Performing calculations based on user choice
if shape_choice == 'circle':
radius = float(input("Enter the radius of the circle: "))
area = circle.calculate_area(radius)
14
circumference = circle.calculate_circumference(radius)
print(f"\nArea of the circle: {area:.2f}")
print(f"Circumference of the circle: {circumference:.2f}")
Output :
Exercise:
1. Create a package named DemoPackage which contains two modules named mathematics
and greets. The mathematics module contains sum, average, power functions, and the
greets module contains the sayHello function.
a) import the module from a package to another program.
b) import a specific function from a module.
2. Explain Intra Package Module.
EVALUATION:
Signature: _______________________
Date : _______________________
15
Experiment No: 7 Date: / /
Aim:- Write a Python program using PIP to install a package and demonstrate its usage.
Objective:
Solution:
Open a terminal or command prompt and use the following command to install the requests
package as an example:
response = requests.get(url)
data = response.json()
# Displaying relevant weather information
if response.status_code == 200:
temperature = data['main']['temp']
weather_description = data['weather'][0]['description']
print(f"\nWeather in {city}:")
print(f"Temperature: {temperature} K")
print(f"Description: {weather_description}")
else:
print(f"Failed to fetch weather data. Error code: {response.status_code}")
# Accepting user input for the city
city_name = input("Enter the city name: ")
# Calling the function to fetch and display weather information
fetch_weather(city_name)
16
Solution:
1.Run the main program:
a. Save the main_program.py file.
b. Open a terminal or command prompt.
c. Navigate to the directory containing main_program.py.
d. Run the program using the command: python main_program.py.
2. Enter a city name:
a. The program will prompt you to enter the name of a city.
3. View the weather information:
a. The program will use the requests package to fetch weather data from the
OpenWeatherMap API.
b. It will display the temperature and weather description for the entered city.
Exercise:
1. Write Steps to install urllib3 package using PIP. Send HTTP requests to any URL and print
status for the same.
2. What is PIP? Write the syntax to install and uninstall python packages.
EVALUATION:
Signature: _______________________
Date : _______________________
17
Experiment No: 8 Date: / /
Aim:- Write a Python program explaining errors, exceptions, and raising exceptions.
Objective:
1. Illustrate common types of errors in Python, including syntax errors and runtime errors.
2. Introduce the concept of exceptions and demonstrate how to handle them.
3. Show how to raise custom exceptions in Python.
def raise_custom_exception():
try:
raise ValueError("This is a custom exception.")
except ValueError as e:
print(f"Caught a custom exception: {e}")
Output :
ZeroDivisionError:
Uncomment # divide_numbers(10, 0) to observe this scenario.
Error: division by zero. Cannot divide by zero.
This block is always executed, whether an exception occurred or not.
TypeError:
Uncomment # divide_numbers(10, "2") to observe this scenario.
Error: unsupported operand type(s) for /: 'int' and 'str'. Make sure both numbers are of the same
type.
This block is always executed, whether an exception occurred or not.
18
Successful Division:
Explanation:
Exercise:
EVALUATION:
Signature: _______________________
Date : _______________________
19
Experiment No: 9 Date: / /
Aim: Write a Python program covering file basics, including creation, reading, and writing.
Objective:
The goal is to create a Python program that demonstrates the basics of file handling, including
creating a file, writing content to it, reading the content back, and finally, displaying the content
to the console. This simple program will help understand how to work with files in Python,
which is a fundamental skill for any Python developer.
create_file(filename): Attempts to create a new file with the given filename. If the file already
exists, it notifies the user.
write_to_file(filename, content): Writes the given content to the specified file. If the file
already exists, it overwrites its content.
read_file(filename): Reads and displays the content of the specified file. If the file does not
exist, it notifies the user.
The main() function demonstrates the usage of these functions by creating a file, writing content
to it, and then reading and displaying the file's content.
20
Expected Output
When you run the above program, it performs the following actions:
It creates a file named example.txt in the current directory (or overwrites it if it already
exists).
It writes the specified content (Hello, this is a test file.\nHere we have some text on multiple
lines.) into the file.
It reads the content of the file back into the program.
Finally, it prints the content of the file to the console.
Exercise:
1. Write a program to read the content of file line by line and write it to another file except
for the lines containing "a" letter in it
2. Write a program that inputs a text file. The program should print all of the unique words
in the file in alphabetical order.
3. Write a program to create a binary file to store Rollno and Name, Search any Rollno and
display name if Rollno found otherwise “Rollno not found”.
4. Write a program to demonstrate the file and file I/O operations.
EVALUATION:
Signature: _______________________
Date : _______________________
21
Experiment No: 10 Date: / /
Aim: Write a Python program using Turtle graphics to draw graphics with loops and
conditions
Theory:
Turtle: In Turtle graphics, a turtle is a graphical object that can move around on a canvas. It has a
position, orientation, and a pen for drawing lines. The turtle can move forward or backward and
turn left or right.
Canvas: The canvas is the area where the turtle moves and draws. It's typically a window or a
graphical interface where shapes and patterns are rendered.
Commands: Turtle graphics provides a set of commands that allow you to control the turtle's
movement and drawing actions. Some common commands include forward(), backward(), left(),
right(), penup(), pendown(), speed(), etc.
Pen: The pen is a drawing tool associated with the turtle. When the pen is down, the turtle draws
a line as it moves. When the pen is up, the turtle moves without drawing. You can control the pen
using penup() and pendown() commands.
Speed: Turtle graphics allows you to control the speed of the turtle's movement. You can set the
speed to adjust how quickly or slowly the turtle moves across the canvas.
Loops and Conditions: You can use loops (such as for or while loops) and conditions (such as if
statements) to create complex shapes and patterns by repeating certain actions or changing the
turtle's behavior based on specific conditions.
Turtle graphics is often used as a tool for teaching basic programming concepts such as loops,
conditions, and functions in a visual and interactive way. It encourages experimentation and
creativity, allowing learners to explore geometric shapes, patterns, and even simple animations.
In the Turtle graphics library, the pen commands control the state of the pen associated with the
turtle, determining whether the turtle will draw lines as it moves or not. Here are the basic syntax
22
and usage of the pen commands:
Pen Down: This command makes the turtle start drawing lines as it moves.
turtle.pendown()
Pen Up: This command lifts the pen, causing the turtle to move without drawing lines.
turtle.penup()
Pen Color: This command sets the color of the pen that the turtle uses to draw lines.
Pen Thickness: This command sets the thickness of the lines drawn by the turtle.
Pen State: You can also check the current state of the pen (up or down) using the isdown()
method.
Example usage:
import turtle
turtle.forward(100) # Moves the turtle forward without drawing
turtle.pendown() # Puts the pen down, so the turtle starts drawing
turtle.forward(100) # Moves the turtle forward, drawing a line
turtle.penup() # Lifts the pen up, so the turtle stops drawing
turtle.forward(100) # Moves the turtle forward without drawing
turtle.done() # Keeps the window open until it's manually closed
In this example, the turtle moves forward 100 units without drawing, then puts the pen down and
moves forward again, drawing a line. After that, it lifts the pen up and moves forward without
drawing another line.
Exercise:
23
Innovative Exercise:
EVALUATION:
Signature: _______________________
Date : _______________________
24