1
Advance Python Programming
Pragramming Questions
UNIT - 1
1. Write a program that finds maximum and minimum numbers
from a list. (repeated 2 times)
CODE
numbers = [10,20,30,40,50]
maximum = max(numbers)
minimum = min(numbers)
print("Minimum of the numbers is", minimum)
print("Maximum of the numbers is", maximum)
OUTPUT
2. Write a program to concatenate two dictionaries into a new one.
(repeated 2 times)
CODE
dict1 = {'a': 1, 'b': 2}
dict2 = {'c': 3, 'd': 4}
combined_dict = dict1 | dict2
print("First dictionary:", dict1)
print("Second dictionary:", dict2)
2
print("Combined dictionary:", combined_dict)
OUTPUT
3. Write how to add, remove an element from a set. Explain why POP
is different from remove.
● Use add() to add a single element
● Use remove() to delete an element (raises an error if element doesn't
exist)
● Use discard() to delete an element safely (no error if element doesn't
exist)
● Use pop() to remove and return an arbitrary element
● Use clear() to remove all elements
pop() removes and returns a random element from the set, while remove()
deletes a specific element you specify.
EXAMPLE
# Create a set
my_set = {1, 2, 3, 4, 5}
print("Original set:", my_set)
# Add an element to a set
my_set.add(6)
print("After adding 6:", my_set)
# Add another element
my_set.add(7)
print("After adding 7:", my_set)
# Remove an element from a set
3
my_set.remove(3)
print("After removing 3:", my_set)
# Try to remove an element that doesn't exist
# my_set.remove(10) # This would raise an error
# Remove an element safely (no error if element doesn't
exist)
my_set.discard(4)
print("After discarding 4:", my_set)
my_set.discard(10) # No error even though 10 isn't in the
set
print("After trying to discard 10:", my_set)
# Remove and return an arbitrary element
popped_element = my_set.pop()
print(f"Popped element: {popped_element}")
print("Set after pop:", my_set)
# Clear all elements
my_set.clear()
print("After clearing the set:", my_set)
OUTPUT
4. List out built-in Dictionary functions. Write a program to
demonstrate dictionary functions and operations.
List of built-in dictionary functions
1. len()
4
2. dict()
3. key()
4. values()
5. items()
6. get()
7. update()
8. del()
9. clear()
CODE
# Create a dictionary
my_dict = {'a': 1, 'b': 2, 'c': 3}
print("Original dictionary:", my_dict)
# len() - Get the number of items in the dictionary
dict_length = len(my_dict)
print("Length of dictionary:", dict_length)
# dict() - Create a dictionary from key-value pairs
new_dict = dict([('x', 10), ('y', 20), ('z', 30)])
print("New dictionary created with dict():", new_dict)
# keys() - Get all keys
all_keys = my_dict.keys()
print("All keys:", all_keys)
# values() - Get all values
all_values = my_dict.values()
print("All values:", all_values)
# items() - Get all key-value pairs
all_items = my_dict.items()
print("All items:", all_items)
5
# get() - Get a value by key (with default if key doesn't
exist)
value_b = my_dict.get('b')
value_d = my_dict.get('d', 'Not found')
print("Value for key 'b':", value_b)
print("Value for key 'd':", value_d)
# update() - Add or update items
my_dict.update({'b': 22, 'd': 4})
print("After update():", my_dict)
# del - Delete a specific item
del my_dict['a']
print("After deleting 'a':", my_dict)
# clear() - Remove all items
my_dict.clear()
print("After clear():", my_dict)
OUTPUT
6
UNIT - 2
1. Write a program to define a module to find the sum of two
numbers. Import the module into another program. (repeated 2
times)
CODE
Module_1.py
def add_numbers(a,b):
print("Sum of a and b is", a+b)
Module_2.py
import module_1
a = int(input("Enter A = "))
b = int(input("Enter B = "))
module_1.add_numbers(a,b)
OUTPUT
2. Write a program to define a module to find the area and
circumference of a circle. Import this module in a program and call
functions from it.
7
CODE
Module_main.py
import math
def area(r):
pi = math.pi
a = pi*r*r
print("Area of circle =", a)
def circum(r):
pi = math.pi
c = 2*pi*r
print("Circumference of the circle =", c)
Module_1.py
import module_main
r = int(input("Enter the radius of yor circle : "))
module_main.area(r)
module_main.circum(r)
OUTPUT
8
UNIT - 3
1. Write a user-defined exception that could be raised when the text
entered by a user consists of less than 10 characters.
CODE
# Define the custom exception
class ShortTextError(Exception):
pass
# Check the text
try:
text = input("Enter text (10+ characters): ")
if len(text) < 10:
raise ShortTextError
print("Text is okay!")
except ShortTextError:
print("Error: Text must be at least 10 characters
long.")
OUTPUT
9
2. Write a program to catch a Divide by Zero Exception with a finally
clause. (repeated 2 times)
CODE
def divide_numbers(dividend, divisor):
try:
quotient = dividend / divisor
print("Answer is : ", quotient)
except ZeroDivisionError:
print("It cannot be divided by zero!")
finally:
print("Program completed.")
dividend = int(input("Numerator : "))
divisor = int(input("Denominator : "))
divide_numbers(dividend, divisor)
OUTPUT
10
3. Develop a function for marks result which contains two arguments
(English and Maths marks). If the value of any argument is less
than 0, raise an error.
CODE
def check_marks(english, maths):
if english < 0 or maths < 0:
raise ValueError("Marks cannot be less than 0")
else:
print("English marks:", english)
print("Maths marks:", maths)
print("Total marks:", english + maths)
# Example usage
try:
print("---Trying Valid Marks---")
check_marks(75, 80) # Valid marks
print("---Trying Invalid Marks---")
check_marks(-5, 80) # Invalid marks (will raise error)
except ValueError as error:
print("Error:", error)
OUTPUT
11
UNIT - 4
1. Write a program to sort all the words in a file and put them in a
list. (repeated 2 times)
CODE
# Open a text file (you can change the file name as needed)
file_name = "sample.txt"
# Open and read the file
with open(file_name, 'r') as file:
# Read the entire file content
content = file.read()
# Split the content into words
# This will split on spaces and remove extra whitespace
words = content.split()
# Sort the words alphabetically
sorted_words = sorted(words)
# Print the sorted list
print("The sorted words are:")
print(sorted_words)
Sample.txt
zippy, puddle, cookie, wobble, igloo,
sprinkle, bubble, noodle, umbrella,
fizzle, quirky, kite, apple, tickle,
jumpy, rainbow, elf, yawn,
12
munch, giggles, vroom, lollipop, doodle, xylophone, oops, hoot.
OUTPUT
2. Write a program that inputs a text file. The program should print
all of the unique words in the file in alphabetical order. (repeated 2
times)
CODE
# Open and read the file named 'sample.txt'
with open('sample.txt', 'r') as file:
# Read all text from the file
text = file.read()
# Split the text into words
# This creates a list of words by splitting at spaces and
removing punctuation
words = text.split()
# Create an empty list to store clean words
clean_words = []
# Clean each word by removing punctuation
for word in words:
# Remove any punctuation from start and end of word (,)
clean_word = word.strip(',')
clean_words.append(clean_word)
13
# Convert list to set to get unique words
unique_words = set(clean_words)
# Convert set back to list and sort alphabetically
sorted_words = sorted(unique_words)
# Print all unique words in alphabetical order
print("Unique words in alphabetical order:")
for word in sorted_words:
print(word)
Sample.txt
zippy, puddle, cookie, wobble, igloo,
sprinkle, bubble, noodle, umbrella,
fizzle, quirky, kite, apple, tickle,
jumpy, rainbow, elf, yawn,
munch, giggles, vroom, lollipop, doodle, xylophone, oops, hoot.
OUTPUT
14
3. Write a program to count all the vowels in a file.
CODE
# Open and read the file
# Open the file
file = open("sample.txt", "r")
# Read all content
content = file.read()
# Close the file
15
# Initialize vowel count to 0
vowel_count = 0
# List of vowels
vowels = ['a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U']
# Check each character in content
for char in content:
# If character is a vowel, increase count
if char in vowels:
vowel_count = vowel_count + 1 # vowel_count += 1
# Print the result
print("Total number of vowels in file: ", vowel_count)
file.close()
Sample.txt
zippy, puddle, cookie, wobble, igloo,
sprinkle, bubble, noodle, umbrella,
fizzle, quirky, kite, apple, tickle,
jumpy, rainbow, elf, yawn,
munch, giggles, vroom, lollipop, doodle, xylophone, oops, hoot.
OUTPUT
4. 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”.
(Write a program to create a binary file to store Seat No and Name.
Search any Seat No and display the name if found, otherwise “Seat No
not found”. )
16
CODE
import pickle
students = [
{'PEN no.': 1, 'NAME': 'Pratham'},
{'PEN no.': 2, 'NAME': 'Bhargav'},
{'PEN no.': 3, 'NAME': 'Rishi'}
]
with open('student.data', 'wb') as file:
for student in students:
pickle.dump(student, file)
def search_rollno(rollno_to_search):
found = False
try:
with open('student.data', 'rb') as file:
while True:
try:
student = pickle.load(file)
if student['PEN no.'] ==
rollno_to_search:
print(f"{student['NAME']}'s no. is
{rollno_to_search}")
found = True
break
except EOFError:
if not found:
print("Roll no. not found")
break
except FileNotFoundError:
print("Student data file not found")
rollno = int(input("Enter PEN no. to search: "))
17
search_rollno(rollno)
OUTPUT
UNIT - 5
1. Write a program to draw a square, rectangle, and circle using
turtle. (repeated 2 times)
CODE
import turtle
# Rectangle
t = turtle.Turtle()
t.shape("arrow")
t.color("black")
t.fd(100)
t.lt(90)
t.fd(100)
t.lt(90)
t.fd(100)
t.lt(90)
t.fd(100)
t.lt(90)
t.penup()
t.lt(180)
# Square
18
t.fd(100)
t.pendown()
t.shape("arrow")
t.color("black")
t.fd(100)
t.lt(90)
t.fd(50)
t.lt(90)
t.fd(100)
t.lt(90)
t.fd(50)
t.penup()
# Circle
t.fd(100)
t.pendown()
t.shape("arrow")
t.color("black")
t.circle(60)
OUTPUT
2. Draw Circle and Triangle shapes using Turtle and fill them with
red color. (repeated 2 times)
19
CODE
import turtle
t = turtle.Turtle()
t.hideturtle()
# Circle
t.penup()
t.fd(100)
t.pendown()
t.color("red")
t.begin_fill()
t.circle(60)
t.end_fill()
#Triangle
t.penup()
t.goto(200, 0)
t.pendown()
t.color("red")
t.begin_fill()
t.goto(200, 100)
t.goto(300, 0)
t.goto(200, 0)
t.end_fill()
OUTPUT
20
3. Write a program to draw a smiling face emoji using turtle.
CODE
import turtle as t
def eye(col, rad):
t.down()
t.fillcolor(col)
t.begin_fill()
t.circle(rad)
t.end_fill()
t.up()
t.fillcolor('yellow')
t.begin_fill()
t.circle(100)
t.end_fill()
t.up()
t.goto(-40, 120)
eye('white', 15)
t.goto(-37, 125)
eye('black', 5)
t.goto(40, 120)
eye('white', 15)
t.goto(40, 125)
eye('black', 5)
t.goto(0,75)
eye('black', 8)
t.goto(-40,85)
t.down()
t.right(90)
t.circle(40,180)
t.up()
t.goto(-10,45)
t.down()
t.right(180)
t.fillcolor('red')
21
t.begin_fill()
t.circle(10,180)
t.end_fill()
t.hideturtle()
OUTPUT
4. Write a program to draw an Indian Flag using Turtle. (repeated 2
times)
CODE
import turtle
t=turtle.Turtle()
w=turtle.Screen()
w.title("India Flag")
t.speed(10)
t.up()
t.goto(-400,260)
t.down()
t.color("orange")
t.begin_fill()
22
t.forward(800)
t.right(90)
t.forward(167)
t.right(90)
t.forward(800)
t.end_fill()
t.color("white")
t.begin_fill()
t.lt(90)
t.forward(167)
t.color("green")
t.begin_fill()
t.forward(167)
t.lt(90)
t.forward(800)
t.lt(90)
t.forward(167)
t.end_fill()
t.up()
t.goto(70, 0)
t.down()
t.color("navy")
t.begin_fill()
t.circle(70)
t.end_fill()
t.up()
t.goto(60, 0)
t.down()
t.color("white")
t.begin_fill()
t.circle(60)
t.end_fill()
t.up()
t.goto(-57, -8)
t.down()
23
t.color("navy")
t.up()
t.goto(20, 0)
t.down()
t.begin_fill()
t.circle(20)
t.end_fill()
t.up()
t.goto(0, 0)
t.down()
t.pensize(2)
for i in range(24):
t.forward(60)
t.backward(60)
t.left(-15)
t.ht()
t.done()
OUTPUT
24
5. Draw circle and star shapes using turtle and fill them with red
color.
CODE
import turtle
t = turtle.Turtle()
t.hideturtle()
# Circle
t.penup()
t.fd(100)
t.pendown()
t.color("red")
t.begin_fill()
t.circle(60)
t.end_fill()
#Star
t.penup()
t.goto(-50, -50)
t.pendown()
t.color("red")
t.begin_fill()
t.forward(100)
t.right(144)
t.forward(100)
t.right(144)
t.forward(100)
t.right(144)
t.forward(100)
t.right(144)
t.forward(100)
t.right(144)
t.end_fill()
turtle.done()
25
OUTPUT