0% found this document useful (0 votes)
194 views

Lab-manual-Advanced Python Programming 4321602

Uploaded by

dhruveshnp
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
194 views

Lab-manual-Advanced Python Programming 4321602

Uploaded by

dhruveshnp
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 24

Sal Institute of Diploma Studies

DEPARTMENT OF INFORMATION TECHNOLOGY

Advanced Python Programming (4321602)

Laboratory Manual
Year: 2023-2024

Prepared By:

Ms. Dhara Prajapati


Mr. Meet Y Pujara

1
Index

Sr Aim Page No Date Marks Signature


No.
FROM TO
1 Write a Python program to
demonstrate string and list
operations.

2 Write a Python program


showcasing built-in functions for
Set manipulation.

3 Write a Python program


highlighting Tuple operations and
functions.

4 Write a Python program


demonstrating built-in functions
for Dictionary manipulation.

5 Write a Python program that


involves creating and importing a
module.

6 Write a Python program


illustrating the creation and
importing of a package.

7 Write a Python program using PIP


to install a package and
demonstrate its usage.

8 Write a Python program


explaining errors, exceptions, and
raising exceptions. .

9 Write a Python program covering


file basics, including creation,
reading, and writing.

10 Write a Python program using


Turtle graphics to draw graphics
with loops and conditions.

2
Experiment No: 1 Date: / /

Aim: Write a Python program to demonstrate string and list operations.

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.

List Operations Section Objectives:


1. Conversion to List:
a. Convert the input string to a list.
2. Appending Symbol:
a. Append an exclamation mark ('!') to the list.
3. Removing Spaces:
a. Remove spaces from the list.
4. Reversed List Display:
a. Display the reversed version of the list.
5. Index of Character 'a':
a. Find and display the index of the character 'a' in the list.
6. Count of Character 'a':
a. Count and display the occurrences of the character 'a' in the list.

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])

# Function to demonstrate list operations


def list_operations(input_string):
# List operations
input_list = list(input_string)
print("\nOriginal List:", input_list)
input_list.append('!')
print("List after appending '!':", input_list)
input_list.remove(' ')
print("List after removing spaces:", input_list)
input_list.reverse()
print("Reversed List:", input_list)
print("Index of 'a':", input_list.index('a'))
print("Count of 'a':", input_list.count('a'))

# Accepting a string input from the user


user_input = input("Enter a string: ")

# String Operations Section


print("\nString Operations Section:")
string_operations(user_input)

# List Operations Section


print("\nList Operations Section:")
list_operations(user_input)

Output :

Enter a string: hello world

String Operations Section:


Original String: hello world
Length of the String: 11
Uppercase: HELLO WORLD

Lowercase: hello world


First 5 characters: hello
Last 5 characters: world
Reversed String: dlrow olleh

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:

Problem Analysis Understanding Timely


Mock Total
& Solution Level Completion (2) (10)
(3) (3)
(2)

Signature: _______________________

Date : _______________________

5
Experiment No: 2 Date: / /

Aim: Write a Python program showcasing built-in functions for Set manipulation.

Objective:

1. Accept two sets from the user.


2. Display the union of the two sets.
3. Display the intersection of the two sets.
4. Display the difference between the two sets.
5. Display the symmetric difference between the two sets.
6. Check if one set is a subset of the other.
7. Check if the sets are disjoint.

# Function to showcase set manipulation


def set_manipulation(set1, set2):
# Displaying the original sets
print("Set 1:", set1)
print("Set 2:", set2)
# Displaying the union of the sets
print("\nUnion of Set 1 and Set 2:", set1.union(set2))
# Displaying the intersection of the sets
print("Intersection of Set 1 and Set 2:", set1.intersection(set2))
# Displaying the difference between the sets
print("Difference (Set 1 - Set 2):", set1.difference(set2))
print("Difference (Set 2 - Set 1):", set2.difference(set1))
# Displaying the symmetric difference between the sets
print("Symmetric Difference:", set1.symmetric_difference(set2))
# Checking if one set is a subset of the other
print("\nIs Set 1 a subset of Set 2:", set1.issubset(set2))
print("Is Set 2 a subset of Set 1:", set2.issubset(set1))
# Checking if sets are disjoint
print("Are Set 1 and Set 2 disjoint:", set1.isdisjoint(set2))
# Accepting sets input from the user
set1 = set(input("Enter elements for Set 1 (comma-separated): ").split(','))
set2 = set(input("Enter elements for Set 2 (comma-separated): ").split(','))
# Calling the function to showcase set manipulation
set_manipulation(set1, set2)

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

1. Write a program to demonstrate the set functions and operations.


2. Demonstrate the use of set operations to find:
a. The union of fruits and vegetables.
b. The intersection of fruits and vegetables.
c. The difference between fruits and vegetables.
d. The symmetric difference between fruits and vegetables.
3. Write a Python program to remove an item from a set if it is present in the set.

EVALUATION:

Problem Analysis Understanding Timely


Mock Total
& Solution Level Completion (2) (10)
(3) (3)
(2)

Signature: _______________________

Date : _______________________

7
Experiment No: 3 Date: / /

Aim:- Write a Python program highlighting Tuple operations and functions.

Objective:

1. Accept two tuples from the user.


2. Concatenate the two tuples and display the result.
3. Display the length of each tuple.
4. Find and display the maximum and minimum elements of each tuple.
5. Display the index of a specific element in each tuple.
6. Check if an element is present in each tuple.
7. Convert each tuple to a list and display the result.

Solution :

# Function to showcase tuple operations


def tuple_operations(tuple1, tuple2):
# Concatenating the two tuples
concatenated_tuple = tuple1 + tuple2
print("Concatenated Tuple:", concatenated_tuple)
# Displaying the length of each tuple
print("Length of Tuple 1:", len(tuple1))
print("Length of Tuple 2:", len(tuple2))
# Finding and displaying the maximum and minimum elements of each tuple
print("Max of Tuple 1:", max(tuple1))
print("Min of Tuple 1:", min(tuple1))
print("Max of Tuple 2:", max(tuple2))
print("Min of Tuple 2:", min(tuple2))
# Displaying the index of a specific element in each tuple
element_to_find = input("Enter an element to find: ")
print("Index of '{}' in Tuple 1:".format(element_to_find), tuple1.index(element_to_find))
print("Index of '{}' in Tuple 2:".format(element_to_find), tuple2.index(element_to_find))
# Checking if an element is present in each tuple
element_to_check = input("Enter an element to check for presence: ")
print("Is '{}' present in Tuple 1:".format(element_to_check), element_to_check in tuple1)
print("Is '{}' present in Tuple 2:".format(element_to_check), element_to_check in tuple2)
# Converting each tuple to a list
list_from_tuple1 = list(tuple1)
list_from_tuple2 = list(tuple2)
print("List from Tuple 1:", list_from_tuple1)
print("List from Tuple 2:", list_from_tuple2)
# Accepting tuples input from the user
tuple1 = tuple(input("Enter elements for Tuple 1 (comma-separated): ").split(','))
tuple2 = tuple(input("Enter elements for Tuple 2 (comma-separated): ").split(','))
# Calling the function to showcase tuple operations
tuple_operations(tuple1, tuple2)

8
Output:

Enter elements for Tuple 1 (comma-separated): 1, 2, 3


Enter elements for Tuple 2 (comma-separated): 4, 5, 6
Concatenated Tuple: ('1', '2', '3', '4', '5', '6')
Length of Tuple 1: 3
Length of Tuple 2: 3
Max of Tuple 1: 3
Min of Tuple 1: 1
Max of Tuple 2: 6
Min of Tuple 2: 4
Enter an element to find: 2
Index of '2' in Tuple 1: 1
Index of '2' in Tuple 2: -1
Enter an element to check for presence: 5
Is '5' present in Tuple 1: False
Is '5' present in Tuple 2: True
List from Tuple 1: ['1', '2', '3']
List from Tuple 2: ['4', '5', '6']

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:

Problem Analysis Understanding Timely


Mock Total
& Solution Level Completion (2) (10)
(3) (3)
(2)

Signature: _______________________

Date : _______________________

9
Experiment No: 4 Date: / /

Aim: Write a Python program demonstrating built-in functions for Dictionary


manipulation.

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.

# Function to showcase dictionary manipulation


def dictionary_manipulation(dict1, dict2):
# Merging the two dictionaries
merged_dict = {**dict1, **dict2}
print("Merged Dictionary:", merged_dict)
# Displaying keys, values, and items of each dictionary
print("\nKeys of Dictionary 1:", dict1.keys())
print("Values of Dictionary 1:", dict1.values())
print("Items of Dictionary 1:", dict1.items())
print("\nKeys of Dictionary 2:", dict2.keys())
print("Values of Dictionary 2:", dict2.values())
print("Items of Dictionary 2:", dict2.items())
# Checking if a specific key is present in each dictionary
key_to_check = input("\nEnter a key to check: ")
print("Is '{}' present in Dictionary 1:".format(key_to_check), key_to_check in dict1)
print("Is '{}' present in Dictionary 2:".format(key_to_check), key_to_check in dict2)
# Updating the value of a specific key in each dictionary
key_to_update = input("Enter a key to update: ")
new_value = input("Enter the new value: ")
dict1[key_to_update] = new_value
dict2[key_to_update] = new_value
print("Updated Dictionary 1:", dict1)
print("Updated Dictionary 2:", dict2)
# Removing a key-value pair from each dictionary
key_to_remove = input("\nEnter a key to remove: ")
dict1.pop(key_to_remove, None)
dict2.pop(key_to_remove, None)
print("Dictionary 1 after removing key '{}':".format(key_to_remove), dict1)
print("Dictionary 2 after removing key '{}':".format(key_to_remove), dict2)

# Checking if the dictionaries are equal


print("\nAre Dictionary 1 and Dictionary 2 equal:", dict1 == dict2)

# Accepting dictionaries input from the user


dict1 = eval(input("Enter Dictionary 1 (in the form of key-value pairs): "))
dict2 = eval(input("Enter Dictionary 2 (in the form of key-value pairs): "))
# Calling the function to showcase dictionary manipulation

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}

Merged Dictionary: {'a': 1, 'b': 2, 'c': 4, 'd': 5, 'e': 6}

Keys of Dictionary 1: dict_keys(['a', 'b', 'c'])


Values of Dictionary 1: dict_values([1, 2, 3])
Items of Dictionary 1: dict_items([('a', 1), ('b', 2), ('c', 3)])

Keys of Dictionary 2: dict_keys(['c', 'd', 'e'])


Values of Dictionary 2: dict_values([4, 5, 6])
Items of Dictionary 2: dict_items([('c', 4), ('d', 5), ('e', 6)])
Enter a key to check: b
Is 'b' present in Dictionary 1: True
Is 'b' present in Dictionary 2: False
Enter a key to update: a
Enter the new value: 10
Updated Dictionary 1: {'a': 10, 'b': 2, 'c': 3}
Updated Dictionary 2: {'c': 4, 'd': 5, 'e': 6, 'a': 10}
Enter a key to remove: d
Dictionary 1 after removing key 'd': {'a': 10, 'b': 2, 'c': 3}
Dictionary 2 after removing key 'd': {'c': 4, 'e': 6, 'a': 10}
Are Dictionary 1 and Dictionary 2 equal: False

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:

Problem Analysis Understanding Timely


Mock Total
& Solution Level Completion (2) (10)
(3) (3)
(2)

Signature: _______________________

Date : _______________________

11
Experiment No: 5 Date: / /

Aim: Write a Python program that involves creating and importing a module.

Objective:

1. Create a Python module named math_operations with functions for addition,


subtraction, multiplication, and division.
2. Import the math_operations module in a main program.
3. Accept two numbers from the user in the main program.
4. Use the functions from the imported module to perform addition, subtraction,
multiplication, and division on the entered numbers.
5. Display the results.

File Name : math_operations.py (Module):

# 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: "))

# Using functions from the imported module


result_addition = math_operations.add(num1, num2)
result_subtraction = math_operations.subtract(num1, num2)

result_multiplication = math_operations.multiply(num1, num2)

result_division = math_operations.divide(num1, num2)

# Displaying the results

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:

Problem Analysis Understanding Timely


Mock Total
& Solution Level Completion (2) (10)
(3) (3)
(2)

Signature: _______________________

Date : _______________________

13
Experiment No: 6 Date: / /

Aim:Write a Python program illustrating the creation and importing of a package.

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 (Main Program):

# 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}")

elif shape_choice == 'rectangle':


length = float(input("Enter the length of the rectangle: "))
width = float(input("Enter the width of the rectangle: "))
area = rectangle.calculate_area(length, width)
perimeter = rectangle.calculate_perimeter(length, width)
print(f"\nArea of the rectangle: {area:.2f}")
print(f"Perimeter of the rectangle: {perimeter:.2f}")
else:
print("Invalid choice. Please choose either 'circle' or 'rectangle'.")

Output :

Choose a shape (circle or rectangle): circle


Enter the radius of the circle: 5
Area of the circle: 78.54
Circumference of the circle: 31.42

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:

Problem Analysis Understanding Timely


Mock Total
& Solution Level Completion (2) (10)
(3) (3)
(2)

Signature: _______________________

Date : _______________________

15
Experiment No: 7 Date: / /

Aim:- Write a Python program using PIP to install a package and demonstrate its usage.

Objective:

1. Install a third-party Python package using pip.


2. Create a Python program that imports and uses functions from the installed package.
3. Demonstrate the functionality of the installed package within the program.

Solution:

Installing the Package:

Open a terminal or command prompt and use the following command to install the requests
package as an example:

pip install requests

main_program.py (Main Program):


# main_program.py
import requests
def fetch_weather(city):
# Using the requests package to fetch weather data from OpenWeatherMap API
api_key = "YOUR_API_KEY" # Replace with your OpenWeatherMap API key
url = f"http://api.openweathermap.org/data/2.5/weather?q={city}&appid={api_key}"

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:

Problem Analysis Understanding Timely


Mock Total
& Solution Level Completion (2) (10)
(3) (3)
(2)

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 divide_numbers(a, b):


try:
result = a / b
print(f"Result of {a} / {b} = {result}")
except ZeroDivisionError as e:
print(f"Error: {e}. Cannot divide by zero.")
except TypeError as e:
print(f"Error: {e}. Make sure both numbers are of the same type.")
except Exception as e:
print(f"Error: {e}. An unexpected error occurred.")
else:
print("No exceptions occurred.")
finally:
print("This block is always executed, whether an exception occurred or not.")

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:

Uncomment # divide_numbers(10, 2) to observe this scenario.


Result of 10 / 2 = 5.0
No exceptions occurred.
This block is always executed, whether an exception occurred or not.
Custom Exception:

Uncomment # raise_custom_exception() to observe this scenario.


Caught a custom exception: This is a custom exception.

Explanation:

1. The divide_numbers function attempts to perform division and handles potential


exceptions like ZeroDivisionError and TypeError.
2. The raise_custom_exception function demonstrates raising a custom exception (ValueError)
and catching it using an exception handler.

Exercise:

1. Write a program to catch on Divide by zero Exception with finally clause.


2. Write a user-defined exception that could be raised when the text entered by a user
consists of less than 10 characters.
3. Write a python program to demonstrate exception handling.

EVALUATION:

Problem Analysis Understanding Timely


Mock Total
& Solution Level Completion (2) (10)
(3) (3)
(2)

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.

# Step 1: Create a file and write content to it


file_name = 'example.txt'
content = 'Hello, this is a test file.\nHere we have some text on multiple lines.'

with open(file_name, 'w') as file:


file.write(content)

print(f'File "{file_name}" has been created and written to.')

# Step 2: Read the content from the file


with open(file_name, 'r') as file:
read_content = file.read()

print('Content of the file is as follows:')


print(read_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.

So, the expected output on the console will be:

File "example.txt" has been created and written to.


Content of the file is as follows:
Hello, this is a test file.
Here we have some text on multiple lines.

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:

Problem Analysis Understanding Timely


Mock Total
& Solution Level Completion (2) (10)
(3) (3)
(2)

Signature: _______________________

Date : _______________________

21
Experiment No: 10 Date: / /

Aim: Write a Python program using Turtle graphics to draw graphics with loops and
conditions

Objective: Turtle graphics is a popular way for introducing programming to beginners. It


provides a simple and intuitive way to draw shapes and patterns using a virtual "turtle" that can
move around on a canvas and leave a trail behind it.

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.

turtle.pencolor("red") # Set pen color to red

Pen Thickness: This command sets the thickness of the lines drawn by the turtle.

turtle.pensize(2) # Set pen thickness to 2 pixels

Pen State: You can also check the current state of the pen (up or down) using the isdown()
method.

pen_is_down = turtle.isdown() # Returns True if pen is down, False otherwise

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:

1. Draw square, rectangle, and circle using Turtle.


2. Draw color-filled shapes (square, rectangle, and circle) using Turtle.
3. Draw a smiling face emoji and rainbow using Turtle.

23
Innovative Exercise:

a) Draw an Indian Flag and an Olympic Symbol using Turtle.


b) Draw a chessboard using Turtle.

EVALUATION:

Problem Analysis Understanding Timely


Mock Total
& Solution Level Completion (2) (10)
(3) (3)
(2)

Signature: _______________________

Date : _______________________

24

You might also like