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

python programming list1[1]

The document contains a series of Python programming exercises and examples covering various topics such as loops, classes, file handling, exception handling, and data structures. Each exercise includes code snippets that demonstrate specific concepts, such as creating classes, using decision-making statements, and performing operations on lists and sets. The document serves as a comprehensive guide for learning Python programming through practical examples.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

python programming list1[1]

The document contains a series of Python programming exercises and examples covering various topics such as loops, classes, file handling, exception handling, and data structures. Each exercise includes code snippets that demonstrate specific concepts, such as creating classes, using decision-making statements, and performing operations on lists and sets. The document serves as a comprehensive guide for learning Python programming through practical examples.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 31

1)Write a program to print following:

12

123

1234

for i in range(1, 5):

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

print(j, end=" ")

print()

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

emp1 = EMPLOYEE(101, "Neha")

emp1.display()
3) Write a program to create dictionary of students that includes their ROLL
NO. and NAME.

i) Add three students in above dictionary

ii) Update name = ‘Shreyas’ of ROLL NO =

iii) Delete information of ROLL NO = 1

students = {}

students[1] = "Neha"

students[2] = "Aarya"

students[3] = "Rohan"

print(students)

students[2] = "Shreyas"

print("\nAfter Updating Roll No 2 to 'Shreyas':")

print(students)

del students[1]

print("\nAfter Deleting Roll No 1:")

print(students)

4) Explain decision making statements If- else, if- elif- else with example.
age = 18

if age >= 18:

print("You are eligible to vote.")

else:

print("You are not eligible to vote.")

………………………

marks = 75

if marks >= 90:

print("Grade: A")

elif marks >= 75:

print("Grade: B")

elif marks >= 60:

print("Grade: C")

else:

print("Grade: D")

5)Write the output of the following output


i) >>> a = [2, 5, 1, 3, 6, 9, 7
>>> a [ 2 : 6] = [ 2, 4, 9, 0]
>>> print (a)
[2, 5, 2, 4, 9, 0, 7]
ii) >>> b = [ “Hello” , “Good” ]
>>> b. append ( “python”
>>> print (b)

['Hello', 'Good', 'python']

iii) >>> t1 = [ 3, 5, 6, 7]
>>> print (t 1 [2])
>>> print (t 1 [–1])
>>> print (t 1 [2 :])
>>> print (t 1 [:])
6
7
[6, 7]
[3, 5, 6, 7]

6) Write a program for package Numpy with example.(Matrix


Addition,subtraction)

import numpy as np

A = np.array([[1, 2], [3, 4]])

B = np.array([[5, 6], [7, 8]])

addition = A + B

subtraction = A - B

print("Matrix 1:\n", matrix1)

print("Matrix 2:\n", matrix2)

print("Addition:\n", addition)

print("Subtraction:\n", subtraction)

7) Write a program to implement the concept of inheritance in python

class Animal:

def speak(self):

print("Animal speaks")
class Dog(Animal):

def bark(self):

print("Dog barks")

d = Dog()

d.speak() # Inherited from Animal

d.bark() # From Dog

8) Explain Try-except block used in exception handling in python with


example.

try:

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

print(100/num)

except:

print("Something went wrong! Cannot divide.")

9) Write a program to open a file in write mode and append some contents at
the end of file.

file = open("myfile.txt", "w")

file.write("original content.\n")

file.close()

file = open("myfile.txt", "a")

file.write("appended content.\n")
file.close()

file = open("myfile.txt", "r")

print(file.read())

file.close()

10)Write down the output of the following Python code


>>>indices=['zero','one','two','three','four','five'

1)>>>indices[:4]
['zero', 'one', 'two', 'three']
2)>>>indices[:-2]
['zero', 'one', 'two', 'three']

11)Write a Python program to find the factorial of a number provided by the


user.

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

fact = 1

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

fact = fact * i

print("Factorial is:", fact)

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

t1 = eval(input("Enter first tuple: "))

t2 = eval(input("Enter second tuple: "))

t1, t2 = t2, t1
print("After swapping:")

print("First tuple:", t1)

print("Second tuple:", t2)

13)Write a program about readline() and readlines() functions in file-


handling.

file = open("example.txt", "w")

file.write("Hello, this is the first line.\n")

file.write("This is the second line.\n")

file.write("Here comes the third line.\n")

file.close()

file = open("example.txt", "r")

print(file.readline()) # Reads first line

print(file.readline()) # Reads second line

file.close()

file = open("example.txt", "r")

lines = file.readlines()

for line in lines:

print(line.strip())

file.close()

14) Write a program 'Self' Parameter .


class Person:

def __init__(self, name, age):

self.name = name

def display(self):

print("Name:", self.name)

person1 = Person("Neha", 21)

person2 = Person("Ravi", 25)

person1.display()

person2.display()

15)Write a program to show user defined exception in Python

class AgeException(Exception):

def __init__(self, message):

self.message = message

super().__init__(self.message)

def check_age(age):

if age < 18:

raise AgeException("Age must be 18 or older")


else:

print("Age is valid.")

try:

age = int(input("Enter your age: "))

check_age(age)

except AgeException as e:

print("Error:", e)

16) Write a Python Program to check if a string is palindrome or not.

def is_palindrome(s):

return s == s[::-1]

string = input("Enter a string: ")

if is_palindrome(string):

print("The string is a palindrome.")

else:

print("The string is not a palindrome.")

17) Write a Python program to calculate sum of digit of given number using
function.

def sum_list(items):

total = 0
for i in items:

total = total+i

return total

my_list=[2,3,4,5,6]

result=sum_list(my_list)

print("Sum of all elements in list:", result)

18) Write a Python Program to accept values from user in a list and find the
largest number and smallest number in a list

n = int(input("Enter the number of elements in the list: "))

user_list = []

for i in range(n):

element = int(input(f"Enter element {i+1}: "))

user_list.append(element)

largest = max(user_list)

smallest = min(user_list)

print("List entered:", user_list)

print("Largest number in the list:", largest)

print("Smallest number in the list:", smallest)


19)Design a class student with data members : name, roll no., department,
mobile no. Create suitable methods for reading and printing student
information.

class Student:

def __init__(self, name, roll_no, department, mobile_no):

self.name = name

self.roll_no = roll_no

self.department = department

self.mobile_no = mobile_no

def display(self):

print("Student Information:")

print("Name:", self.name)

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

print("Department:", self.department)

print("Mobile No:", self.mobile_no)

student1 = Student("Neha", 101, "Computer Science", "1234567890")

student1.display()

20)Write a program for inheritance in Python.

class Animal:

def __init__(self, name):


self.name = name

def speak(self):

print(f"{self.name} makes a sound")

class Dog(Animal):

def speak(self):

print(f"{self.name} barks")

animal = Animal("Generic Animal")

dog = Dog("Buddy")

animal.speak()

dog.speak()

21)Write python program to display output like

2
4 6 8
10 12 14 16 18

for i in range(2, 3, 2):

print(i, end=" ")

print()

for i in range(4, 9, 2):


print(i, end=" ")

print()

for i in range(10, 19, 2):

print(i, end=" ")

22)Write python program using module, show how to write and use module
by importing it.

T = (‘spam’, ‘Spam’, ‘SPAM!’, ‘SaPm’)


print (T[2])
print (T[-2])
print (T[2:])
print (List (T))

Create a module (Let's name it my_module.py):

T = ('spam', 'Spam', 'SPAM!', 'SaPm')

# Function to return the tuple T

def get_tuple():

return T

# Function to convert tuple to list

def list_from_tuple():

return list(T)

Use the module by importing it:

main_program.py:
# Importing the module

import my_module

# Accessing the tuple T from the module

T = my_module.get_tuple()

# Displaying outputs

print(T[2]) # 'SPAM!'

print(T[-2]) # 'SPAM!'

print(T[2:]) # ('SPAM!', 'SaPm')

print(my_module.list_from_tuple()) # ['spam', 'Spam', 'SPAM!', 'SaPm']

23) Write a Python program to create user defined exception that will check
whether the password is correct or not.

# User-defined exception

class PasswordError(Exception):

pass

# Function to check password

def check_password(password):

correct_password = "mypassword123"
if password != correct_password:

raise PasswordError("Incorrect password! Please try again.")

else:

print("Password is correct!")

# Accept password from user

password = input("Enter your password: ")

# Check the password using try-except block

try:

check_password(password)

except PasswordError as e:

print(e)

24)Write a program for overloading and overriding in python.

# Parent class for Overriding example

class Animal:

def sound(self):

print("Animal makes a sound.")

# Child class that overrides the method of parent class

class Dog(Animal):

def sound(self):
print("Dog barks.")

# Parent class for Overloading example

class Calculator:

# Overloading using default arguments

def add(self, a, b=0, c=0):

return a + b + c

# Create objects for Overriding and Overloading examples

animal = Animal()

dog = Dog()

# Call the overridden method (Overriding)

animal.sound() # Animal makes a sound.

dog.sound() # Dog barks.

# Create object for Calculator (Overloading)

calc = Calculator()

# Call the overloaded method with different numbers of arguments

print(calc.add(5)) #5

print(calc.add(5, 10)) # 15
print(calc.add(5, 10, 15)) # 30

25)WAP to read contents of first.txt file and write same content in second.txt
file.

# Open the first file in read mode and second file in write mode

with open('first.txt', 'r') as file1, open('second.txt', 'w') as file2:

content = file1.read() # Read content of first file

file2.write(content) # Write the content to second file

26)Write a program for seek ( ) and tell ( ) function for file pointer
manipulation in python .

# Open a file in read mode

with open('file.txt', 'r') as file:

print("File position before seek:", file.tell())

# Move the file pointer to the 5th byte from the start

file.seek(5)

print("File position after seek:", file.tell())

# Read content from the file

content = file.read()

print("Content read from the file:", content)

27)Write a program to create class student with Roll no. and Name and
display its contents.
class Student:

def __init__(self, roll_no, name):

self.roll_no = roll_no

self.name = name

def display(self):

print(f"Roll No: {self.roll_no}, Name: {self.name}")

# Create a Student object and display details

student1 = Student(101, "Neha")

student1.display()

28)Write a program for four built-in functions on set.

# Creating a set

my_set = {1, 2, 3, 4, 5}

# 1. Add an element

my_set.add(6)

# 2. Remove an element

my_set.remove(4)

# 3. Clear the set


my_set.clear()

# 4. Copy the set

new_set = my_set.copy()

# Display the set

print("New Set:", new_set)

29)Write a program for bitwise operators in Python .

a = 10 # 1010 in binary

b = 4 # 0100 in binary

# Bitwise AND

print(a & b)

# Bitwise OR

print(a | b)

# Bitwise XOR

print(a ^ b)

# Bitwise NOT

print(~a)
# Bitwise Left Shift

print(a << 1)

# Bitwise Right Shift

print(a >> 1)

30)Write python program to illustrate if else ladder.

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

if num > 0:

print("Positive number")

elif num < 0:

print("Negative number")

else:

print("Zero")

31)Write a program for any four operation of List.

my_list = [1, 2, 3, 4, 5]

# 1. Append an element

my_list.append(6)

# 2. Insert an element at a specific position


my_list.insert(2, 7)

# 3. Remove an element

my_list.remove(4)

# 4. Pop the last element

my_list.pop()

print(my_list)

32)Write Python code for finding greatest among four numbers

numbers = [int(input(f"Enter number {i+1}: "))

for i in range(4)]

print("Greatest number:", max(numbers))

33)Write python code to count frequency of each characters in a given file

filename = "file.txt"

with open(filename, 'r') as file:

text = file.read()

char_count = {}

for char in text:

if char.isalpha():

char_count[char] = char_count.get(char, 0) + 1
print(char_count)

34)Design a class student with data members; Name, roll number address
Create suitable method for reading and printing students details.

class Student:

def __init__(self, name, roll_no, address):

self.name = name

self.roll_no = roll_no

self.address = address

def display(self):

print(f"Name: {self.name}, Roll No: {self.roll_no}, Address: {self.address}")

# Create and display student information

student = Student("Neha", 101, "Mumbai")

student.display()

35)Create a parent class named Animals and a child class Herbivorous which
will extend the class Animal. In the child class Herbivorous over side the
method feed ( ). Create a object.

class Animal:

def feed(self):

print("Animal is eating.")
class Herbivorous(Animal):

def feed(self):

print("Herbivorous animal is eating plants.")

# Create object of Herbivorous class

herbivore = Herbivorous()

herbivore.feed()

36)Print the following pattern using loop:

1010101
10101
101
1

for i in range(4, 0, -1):

for j in range(i):

print("1", end=" ")

print("0", end=" " if j < i-1 else "")

print()

37)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 = {1, 2, 3, 4, 5}

# ii) Access set elements

print(my_set)

# iii) Update set by adding one element

my_set.add(6)

# iv) Remove one element

my_set.remove(3)

print(my_set)

38)What is the output of the following program?

a) dict1 = {‘Google’ : 1, ‘Facebook’ : 2, ‘Microsoft’ :


b) dict2 = {‘GFG’ : 1, ‘Microsoft’ : 2, ‘Youtube’ :
c) dict1⋅update(dict2);
for key, values in dictl⋅items( ):
print (key, values)

Google 1

Facebook 2

Microsoft 2

GFG 1

Youtube 3
39) Write a python program that takes a number and checks whether it is a
palindrome.

number = input("Enter a number: ")

if number == number[::-1]:

print(f"{number} is a palindrome.")

else:

print(f"{number} is not a palindrome.")

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

Create a file program_name.py:

def get_program_name():
return "My Python Program"

Main Python Program:

import program_name
print("Program name:", program_name.get_program_name())

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

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

digit_sum = sum(int(digit) for digit in str(number))

print("Sum of digits:", digit_sum)

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

def count_cases(s):

upper_count = sum(1 for c in s if c.isupper())

lower_count = sum(1 for c in s if c.islower())


return upper_count, lower_count

text = input("Enter a string: ")

upper, lower = count_cases(text)

print(f"Uppercase letters: {upper}, Lowercase letters: {lower}")

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

44)Write a python program to generate five random integers between 10 and


50 using numpy library.

import numpy as np

random_numbers = np.random.randint(10, 51, 5)

print(random_numbers)

45)Write a Python program to create a class ‘Diploma’ having a method


‘getdiploma’ that prints “I got a diploma”. It has two subclasses namely ‘CO’
and ‘IF’ each having a method with the same name that prints “I am with CO
diploma” and ‘I am with IF diploma’ respectively. Call the method by creating
an object of each of the three classes

class Diploma:

def getdiploma(self):

print("I got a diploma.")

class CO(Diploma):

def getdiploma(self):

print("I am with CO diploma.")


class IF(Diploma):

def getdiploma(self):

print("I am with IF diploma.")

# Create objects and call methods

diploma = Diploma()

co = CO()

if_ = IF()

diploma.getdiploma()

co.getdiploma()

if_.getdiploma()

46) Write a Python program to create user defined exception that will check
whether the password is correct or not.

# User-defined exception

class PasswordError(Exception):

pass

# Function to check password

def check_password(password):

correct_password = "mypassword123"
if password != correct_password:

raise PasswordError("Incorrect password! Please try again.")

else:

print("Password is correct!")

# Accept password from user

password = input("Enter your password: ")

# Check the password using try-except block

try:

check_password(password)

except PasswordError as e:

print(e)

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

try:

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

result = 10 / num

except ZeroDivisionError:

print("Error: Division by zero.")

48)Design a class student with data members; Name, Roll No., Address. Create
suitable method for reading and printing students detail

class Student:
def __init__(self, name, roll_no, address):

self.name = name

self.roll_no = roll_no

self.address = address

def display(self):

print(f"Name: {self.name}, Roll No: {self.roll_no}, Address: {self.address}")

# Create and display student information

student = Student("Neha", 101, "Mumbai")

student.display()

49)Explain Try-except-else-finally block used in exception handling in Python


with example.

try:

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

result = 10 / x

except ZeroDivisionError:

print("Error: Division by zero.")

else:

print(f"Result: {result}")

finally:
print("Execution finished.")
50)Write a Python program to create a class ‘Diploma’ having a method ‘getdiploma’ that
prints “I got a diploma”. It has two subclasses namely ‘CO’ and ‘IF’ each having a method
with the same name that prints “I am with CO diploma” and ‘I am with IF diploma’
respectively. Call the method by creating an object of each of the three classes

class Diploma:

def getdiploma(self):

print("I got a diploma.")

class CO(Diploma):

def getdiploma(self):

print("I am with CO diploma.")

class IF(Diploma):

def getdiploma(self):

print("I am with IF diploma.")

# Create objects and call methods

diploma = Diploma()

co = CO()

if_ = IF()

diploma.getdiploma()

co.getdiploma()
if_.getdiploma()

You might also like