0% found this document useful (0 votes)
6 views12 pages

4marks Programs

The document contains various Python programming tasks including printing patterns, creating classes, performing arithmetic operations using modules, handling dictionaries, sets, and exceptions, as well as reading and writing files. Each task is accompanied by code snippets demonstrating the implementation of the described functionality. It also includes examples of user-defined packages, method overloading, and error handling.

Uploaded by

sunnygaikwad4747
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)
6 views12 pages

4marks Programs

The document contains various Python programming tasks including printing patterns, creating classes, performing arithmetic operations using modules, handling dictionaries, sets, and exceptions, as well as reading and writing files. Each task is accompanied by code snippets demonstrating the implementation of the described functionality. It also includes examples of user-defined packages, method overloading, and error handling.

Uploaded by

sunnygaikwad4747
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
You are on page 1/ 12

4marks

a)Write a program to print following:

1
12
123
1234

Answer:

for i in range(1, 5):

for j in range(1, i + 1):

print(j, end=' ')

print()

Write a program to create class EMPLOYEE with ID and NAME and display its contents.

class EMPLOYEE:

def __init__(self, emp_id, name):

self.emp_id = emp_id

self.name = name

def display(self):

print("Employee ID:", self.emp_id)

print("Employee Name:", self.name)

e1 = EMPLOYEE(101, "John")

e1.display()

Write a program for importing module for addition and substraction of two numbers.
Mymath.py

def add(a, b):

return a + b

def subtract(a, b):

return a – b

main.py

import mymath

a = 10

b=5

print("Addition:", mymath.add(a, b))

print("Subtraction:", mymath.subtract(a, b))

Write a program to create dictionary of students that includes their ROLL NO. and NAME.

students = {}
print("Step 1: Adding three students")

students[1] = "Amit"

students[2] = "Rahul"

students[3] = "Sneha"

print(students)

print("\n Updating name of Roll No 2 to 'Shreyas'")

students[2] = "Shreyas"

print(students)

print("\n Deleting student with Roll No 1")

del students[1]

print(students)

print("\n Student List:")

for roll_no, name in students.items():

print("Roll No:", roll_no, "Name:", name)

Write a program illustrating use of user defined package in python.

1. Create a package folder

Create a folder named mypackage.

Inside mypackage, create a file:

operations.py

def multiply(a, b):


return a * b

def divide(a, b):


if b != 0:
return a / b
else:
return "Division by zero not allowed"
2. In the main file (outside the folder)
main.py

from mypackage import operations

a = 20
b=5

print("Multiplication:", operations.multiply(a, b))


print("Division:", operations.divide(a, b))

Output:

Multiplication: 100
Division: 4.0

Write a Python program to find the factorial of a number provided by the user.

num = int(input("Enter a number: "))

factorial = 1

if num < 0:

print("Factorial does not exist for negative numbers.")

else:

for i in range(1, num + 1):

factorial *= i

print("Factorial of", num, "is", factorial)

Write a python program to input any two tuples and interchange the tuple variables.

# Input two tuples

t1 = tuple(input("Enter elements of first tuple (no spaces): "))

t2 = tuple(input("Enter elements of second tuple (no spaces): "))

# Swap the tuples


t1, t2 = t2, t1

# Display swapped tuples

print("After swapping:")

print("First tuple:", t1)

print("Second tuple:", t2)

Write a program to show user defined exception in Python.

# Define custom exception

class MyException(Exception):

pass

# Check condition and raise exception

num = int(input("Enter a positive number: "))

if num < 0:

raise MyException("Negative number not allowed")

else:

print("You entered:", num)

output::-

Enter a positive number: -5

Traceback (most recent call last):

...

__main__.MyException: Negative number not allowed

Print the following pattern using loop:

1010101

10101

101

1
# Set number of rows

rows = 4

# Loop through rows

for i in range(rows):

# Print leading spaces

print(" " * i, end="")

# Print 1 0 pattern

for j in range(2 * (rows - i) - 1):

print((j + 1)%2, end=" ")

print() # New line

Write python program to perform following operations on set.

i) Create set of five elements

ii) Access set elements

iii) Update set by adding one element

iv) Remove one element from set

# i) Create a set of five elements

my_set = {10, 20, 30, 40, 50}

print("Set after creation:", my_set)

# ii) Access set elements (Sets are unordered, so accessing will show all elements)

print("Accessed elements of the set:", my_set)


# iii) Update set by adding one element

my_set.add(60)

print("Set after adding an element:", my_set)

# iv) Remove one element from the set

my_set.remove(20) # Removing an element (20 in this case)

print("Set after removing an element:", my_set)

output:::

Set after creation: {50, 20, 40, 10, 30}

Accessed elements of the set: {50, 20, 40, 10, 30}

Set after adding an element: {50, 20, 40, 10, 60, 30}

Set after removing an element: {50, 40, 10, 60, 30}

What is the output of the following program?

dict1 = {‘Google’ : 1, ‘Facebook’ : 2, ‘Microsoft’ : 3}

dict2 = {‘GFG’ : 1, ‘Microsoft’ : 2, ‘Youtube’ : 3}

dict1⋅update(dict2);

for key, values in dictl⋅items( ):

print (key, values)

answer:::---

Google 1
Facebook 2

Microsoft 2

GFG 1

Youtube 3

Write a python program that takes a number and checks whether it is a palindrome.

# Input number from user

num = int(input("Enter a number: "))

# Convert number to string to check palindrome

reverse_num = str(num)[::-1]

# Check if number is a palindrome

if str(num) == reverse_num:

print(f"{num} is a palindrome")

else:

print(f"{num} is not a palindrome")

Write a python program to create a user defined module that will ask your program name and
display the name of the program.

Step 1: Create the module program_name_module.py


# program_name_module.py

def display_program_name():
program_name = input("Enter your program name: ")
print("The name of your program is:", program_name)

Step 2: Main program that uses the module


# main_program.py

# Importing the user-defined module


import program_name_module

# Calling the function from the module


program_name_module.display_program_name()

Output:
Enter your program name: My First Program
The name of your program is: My First Program

Write a python program takes in a number and find the sum of digits in a number.

# Input number from user


num = int(input("Enter a number: "))

# Initialize sum to 0
sum_digits = 0

# Loop through each digit in the number


while num > 0:
sum_digits += num % 10 # Add last digit to sum
num = num // 10 # Remove last digit

# Display the sum of digits


print("Sum of digits:", sum_digits)

output::-

Enter a number: 12
Sum of digits: 3

Write a program function that accepts a string and calculate the number of uppercase letters and
lower case letters.

def count_letters(s):
upper = sum(1 for c in s if c.isupper())
lower = sum(1 for c in s if c.islower())
print(f"Uppercase: {upper}, Lowercase: {lower}")
count_letters("Hello World")

Uppercase: 2, Lowercase: 8

Write a python program to create class student with roll-no and display its contents.
class Student:

def __init__(self, roll_no):

self.roll_no = roll_no

def display(self):

print("Roll Number:", self.roll_no)

student1 = Student(101)

student1.display()

Write a program illustrating use of user defined package in python.(repeated)

1. Create a package folder

Create a folder named mypackage.

Inside mypackage, create a file:

operations.py

def multiply(a, b):


return a * b

def divide(a, b):


if b != 0:
return a / b
else:
return "Division by zero not allowed"

2. In the main file (outside the folder)


main.py

from mypackage import operations

a = 20
b=5

print("Multiplication:", operations.multiply(a, b))


print("Division:", operations.divide(a, b))

Output:
Multiplication: 100
Division: 4.0
Illustrate with example method overloading.

Python does not support traditional method overloading like some other languages (e.g., Java or C++),
but you can simulate method overloading using default arguments or *args.

class Calculator:
def add(self, a=0, b=0, c=0):
return a + b + c

calc = Calculator()

print("Sum of 2 numbers:", calc.add(10, 20))


print("Sum of 3 numbers:", calc.add(10, 20, 30))
print("Sum of 1 number:", calc.add(10))

Output:
Sum of 2 numbers: 30
Sum of 3 numbers: 60
Sum of 1 number: 10

Write a Python program to check for zero division errors exception.

try:

dividend = int(input("Enter a dividend: "))

divisor = int(input("Enter a divisor: "))

result = dividend / divisor

print("Result:", result)

except ZeroDivisionError:

print("Error: Division by zero is not allowed.")

OP:

Enter a dividend: 3

Enter a divisor: 0

Error: Division by zero is not allowed.


Write the output for the following if the variable fruit = ‘banana’.

>> fruit [:3]

>> fruit [3:]

>> fruit [3:3]

>> fruit [:]

fruit = 'banana'

fruit[:3] → 'ban'

fruit[3:] → 'ana'

fruit[3:3] → ''

fruit[:] → 'banana'

Write a Python program to read contents from “a.txt” and write same contents in “b.txt”

# Read from a.txt

with open("a.txt", "r") as file_a:

data = file_a.read()

print("data is read")

# Write to b.txt

with open("b.txt", "w") as file_b:

file_b.write(data)

print("data is written")

You might also like