python record(AIML)
python record(AIML)
Program :-
num=[0,1]
for i in range (2,7):
num.append(num[i-1]+num[i-2])
print(num)
OUTPUT:-
[0, 1, 1, 2, 3, 5, 8]
else:
largest = number3
#print the largest of the three numbers
print("The largest number is = " ,largest)
OUTPUT:-
enter the first number 45
enter the second number78
enter the third number34
The largest number is = 78
Aim :- write a python program tocheck the whether the given number is
Armstrong ( or ) Not ?
Program :
number = int(input("enter the number"))
temp = number
length = len(str(number))
sum1 = 0
while number!=0:
rem = number%10
sum1 = sum1+(rem**length)
number=number//10
if temp==sum1:
print("the given number is armstrong number")
else:
print("the given number is not armstrong number")
output:-
OUTPUT :-
1).Enter a number: 5
Factorial of 5 is 120
2).Enter a number: -3
Factorial is not defined for negative numbers.
Program :-
# input from user
num = int(input("enter the number"))
temp = num
reverse = 0
#logic to find palindrome
while temp > 0 :
remainder = temp % 10
reverse = ( reverse * 10 ) +remainder
temp = temp //10
#compare the the two variables
if num == reverse :
print("palindrome")
else:
print("not a palindrome")
OUTPUT :-
1) enter the number 121
palindrome
2) enter the number 786
not a palindrome
Aim :- write a python program to check the given number is prime or not.
Program :-
number = int(input("enter the number"))
if number <= 1:
print(f"{number} is not a prime number")
else:
is_prime = True
for i in range(2, number):
if number % i == 0:
is_prime = False
break
if is_prime:
print(f"{number} is a prime number")
else:
print(f"{number} is not a prime number")
OUTPUT :-
1) enter the number 6
6 is not a prime number
Aim :- Write a python program to swap the two numbers without using another
Variable .
Program :-
a = int(input("enter the number"))
b = int(input("enter the number"))
a, b = b, a
print("After swapping:")
print("a =", a)
print("b =", b)
""" another logic to swap the two numbers"""
a=5
b = 10
a=a+b
b=a-b
a=a-b
# Print the results
print("After swapping:")
print("a =", a)
print("b =", b)
OUTPUT :-
enter the number 5
enter the number8
After swapping:
a=8
b=5
After swapping:
a = 10
b=5
print('****arithematic operations*****\n' );
# Addition
a=5+3 #8
# Subtraction
b = 10 - 4 #6
# Multiplication
c=7*2 # 14
# Division
d = 15 / 4 # 3.75
# Floor Division
e = 15 // 4 #3
# Modulus
f = 15 % 4 #3
#Exponentiation
g = 2 ** 3 #8
print(f" a = {a}, b = {b}, c = {c}, d = {d}, e = {e}, f = {f}\n")
# Bitwise OR
b=5|3 # 7 (0101 | 0011)
# Bitwise XOR
c=5^3 # 6 (0101 ^ 0011)
# Bitwise NOT
d = ~5 # -6 (~0101)
# Left shift
e = 5 << 1 # 10 (0101 << 1)
# Right shift
f = 5 >> 1 # 2 (0101 >> 1)
print(f" a = {a}, b = {b}, c = {c}, d = {d}, e = {e}, f = {f}\n")
# Is
a = (5 is 5) # True
# Is not
b = (5 is not 3) # True
print(f" a = {a} ,b = {b}\n")
# Ternary operator
age = 15
status = "adult"if age >= 18 else "minor" # "adult"
print(status)
OUTPUT :-
****arithematic operations*****
a = 8, b = 6, c = 14, d = 3.75, e = 3, f = 3
15
12
24
3.0
1.0
1.0
******5. Bitwise Operators******
a = 1, b = 7, c = 6, d = -6, e = 10, f = 2
x = True , y = True
*******7. Identity Operators ********
a = True ,b = True
minor
FUNCTIONS
Aim :- Write a python program to find the factorial of a given number with using
Recursion.
Program :-
def factorial(n):
if n == 0 or n == 1:
return 1
else:
return n * factorial(n - 1)
# Input from the user
num = int(input("Enter a number: "))
OUTPUT :-
Positional arguments (args):
1
2
3
Keyword arguments (kwargs):
name: Alice
age: 30
2) Enter a number: 4
Enter the start of the range: 1
Enter the end of the range: 3
4 is not within the range 1 to 3
Aim :- Write a python program to implements a basic calculates with addition ,
subtraction , multiplication , division.
Program :-
# Function for basic arthematic operations
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 "can't Division by zero."
return x / y
# Start the while loop
while True:
# Display options
print("\nSelect operation:")
print("1. Add")
print("2. Subtract")
print("3. Multiply")
print("4. Divide")
# Take user's choice
choice = input("Enter choice (1/2/3/4): ")
# Take two inputs from the user
x, y = map(int, input("Enter two numbers separated by space: ").split())
# Perform the chosen operation
if choice == '1':
print(f"Result: {x} + {y} = {add(x, y)}")
elif choice == '2':
print(f"Result: {x} - {y} = {subtract(x, y)}")
elif choice == '3':
print(f"Result: {x} * {y} = {multiply(x, y)}")
elif choice == '4':
print(f"Result: {x} / {y} = {divide(x, y)}")
else:
print("Invalid choice. Please try again.")
# Ask the user if they want to continue
user_input = input("\nDo you want to perform another calculation? (yes/no): ").lower()
if user_input != 'yes':
break
print("\nThank you for using the calculator!")
OUTPUT :-
1) Select operation:
1. Add
2. Subtract
3. Multiply
4. Divide
Enter choice (1/2/3/4): 1
Enter two numbers separated by space: 5 8
Result: 5 + 8 = 13
Do you want to perform another calculation? (yes/no): yes
2) Select operation:
1. Add
2. Subtract
3. Multiply
4. Divide
Enter choice (1/2/3/4): 2
Enter two numbers separated by space: 9 4
Result: 9 - 4 = 5
Do you want to perform another calculation? (yes/no): no
Thank you for using the calculator!
Strings :-
Aim :- Write a python program to print first and last letters.
Program :-
def first_last(sentence):
words = sentence.split()
for i in words:
if len(i)>1 :
print(f"first : {i[0]} , last : {i[-1]}")
else:
print(f"first and last word : {i[0]}")
# input from the user
sentence = input("enter a sentence:")
first_last(sentence)
OUTPUT :-
enter a sentence: vignans nirula institute of technology and science for women
first : v , last : s
first : n , last : a
first : i , last : e
first : o , last : f
first : t , last : y
first : a , last : d
first : s , last : e
first : f , last : r
first : w , last : n
OUTPUT:-
Enter a string: pythonprogramming
The character 'p' appears 2 times, which is the maximum frequency.
Aim : - Write a python program to find how many no.of digits and alphabets in a
string.
Program :-
string = input("Enter a string: ")
digitcount = 0
alphacount = 0
othercount = 0
# Count digits, alphabets, and other characters
for char in string:
if char.isdigit():
digitcount += 1
elif char.isalpha():
alphacount += 1
else:
othercount += 1
# Print the results
print("Number of digits:", digitcount)
print("Number of alphabets:", alphacount)
print("Number of other characters:", othercount)
OUTPUT:-
Enter a string: python 4567 @3%$ programming
Number of digits: 5
Number of alphabets: 17
Number of other characters: 6
OUTPUT :-
enter a sentence: python programming
joined string python-programming
Aim :- write a python program check if the string is starts with digits or alphabets.
Program :-
string = input("Enter a string: ")
if string and string[0].isalpha(): # Check if the string starts with an alphabet
print("The string starts with alphabet.")
else:
print("The string does not start with alphabet.")
# Count the number of other characters(excluding alphabets and digits)
othercount = sum(1 for char in string if not char.isalnum())
print("Number of other characters:", othercount)
OUTPUT :-
1) Enter a string: cse-data science
The string starts with alphabet.
Number of other characters: 2
OUTPUT :-
Enter a string: abcdefgh
String with alternative characters capitalized: AbCdEfGh
Lists:-
Aim :- write a python program to find the frequency of a list.
Program :-
numbers = list(map(int, input("Enter numbers separated by spaces: ").split()))
k = int(input("Enter the frequency (k): "))
# Print elements with frequency greater than k
print(f"Elements with frequency greater than {k}:")
for num in set(numbers):
if numbers.count(num) > k:
print(num)
OUTPUT :-
Enter numbers separated by spaces: 1 2 3 3 4 5 5 6 4 3 4
Enter the frequency (k): 2
Elements with frequency greater than 2:
3
4
OUTPUT :-
Enter numbers separated by spaces: 5 3 8 6 9
Squared elements in reverse order: [81, 36, 64, 9, 25]
Aim :- write a python program to print largest and smallest numbers in given list
Program :-
def largest_smallest(num):
largest = max(num)
smallest = min(num)
return largest, smallest
OUTPUT :-
Enter numbers separated by spaces: 4 5 6 2 9 8
Largest number is: 9 and Smallest number is: 2
Aim :- write a python program to swap the elements in the list.
Program :-
numbers = list(map(int, input("Enter numbers separated by spaces: ").split()))
if len(numbers) > 1:
numbers[0], numbers[-1] = numbers[-1], numbers[0]
print(f"List after interchange: {numbers}")
OUTPUT :-
Enter numbers separated by spaces: 4 3 7 6
List after interchange: [6, 3, 7, 4]
Program :-
numbers = list(map(int, input("Enter numbers separated by spaces: ").split()))
# Remove all negative values
filternumbers = [num for num in numbers if num >= 0]
print("List after removing all negative values:", filter_numbers)
OUTPUT :-
Enter numbers separated by spaces: 8 -2 -7 5 9 0
List after removing all negative values: [8, 5, 9, 0]
Program :-
strings = input("Enter strings separated by spaces: ").split()
list = [s for s in strings if s]
print(f"List without empty strings: {list}")
OUTPUT :-
Enter strings separated by spaces: CSE EEE AI ECE IT
List without empty strings: ['CSE', 'EEE', 'AI', 'ECE', 'IT']
Program :-
numbers = list(map(int, input("Enter numbers separated by spaces: ").split()))
mid = len(numbers) // 2
first_half = numbers[:mid]
second_half = numbers[mid:]
# Display the two halves
print(f"First half: {first_half}")
print(f"Second half: {second_half}")
OUTPUT :-
Enter numbers separated by spaces: 9 6 8 4 3 1 0
First half: [9, 6, 8]
Second half: [4, 3, 1, 0]
Aim :- write a python program to remove all occurrence of a element.
Program :-
numbers = list(map(int, input("Enter numbers separated by spaces: ").split()))
element_remove = int(input("Enter the element to remove: "))
filter_numbers = [num for num in numbers if num != element_remove]
# Print the modified list
print("List after removing all occurrences of",element_remove, ":", filter_numbers)
OUTPUT :-
Enter numbers separated by spaces: 5 3 7 3 1 2 2 1 3 5 7
Enter the element to remove: 3
List after removing all occurrences of 3 : [5, 7, 1, 2, 2, 1, 5, 7]
Aim :- write a python program to find all possible combinations of a list with three
elements without using built in methods.
Program :-
# Input: Get list of three elements from user
numbers = list(map(int, input("Enter three elements separated by spaces: ").split()))
# Find all combinations without repetition
print("All possible combinations:")
for i in range(3):
for j in range(3):
for k in range(3):
if i != j and j != k and i != k:
print([numbers[i], numbers[j], numbers[k]])
OUTPUT:-
Enter three elements separated by spaces: 7 6 5
All possible combinations:
[7, 6, 5]
[7, 5, 6]
[6, 7, 5]
[6, 5, 7]
[5, 7, 6]
[5, 6, 7]
Aim :- write a python program to count and filter odd and even numbers of a given list
using loops
Program :-
numbers = list(map(int, input("Enter numbers separated by spaces: ").split()))
# Filter even and odd numbers
even_num = [num for num in numbers if num % 2 == 0]
odd_num = [num for num in numbers if num % 2 != 0]
OUTPUT :-
Enter numbers separated by spaces: 4 6 5 2 3 1 8 7 0 9
Even numbers: [4, 6, 2, 8, 0]
Count of even numbers: 5
Odd numbers: [5, 3, 1, 7, 9]
Count of odd numbers: 5
Tuples:-
Aim :- write a program based on the Tuple operations.
Program :-
#Basic Tuple Operations
print(len((1,2,3,4,5,6)))
print((1,2,3) + (4,5,6))
print(('Good..')*3)
print(5 in (1,2,3,4,5,6,7,8,9,10))
for i in (1,2,3,4,5,6,7,8,9,10):
print(i,end = '')
Tup1 = (1,2,3,4,5)
Tup2 = (1,2,3,4,5)
print(Tup1 < Tup2)
print(max(1,0,3,8,2,9))
print(min(1,0,3,8,2,9))
print(tuple("Hello"))
print(tuple([1,2,3,4,5]))
OUTPUT :-
6
(1, 2, 3, 4, 5, 6)
Good..Good..Good..
True
12345678910False
9
0
('H', 'e', 'l', 'l', 'o')
(1, 2, 3, 4, 5)
Tup1 = (1,2,3,4,5)
Tup2 = (6,7,8,9,10)
Tup3 = Tup1 + Tup2
print(Tup3)
OUTPUT :-
quotient = 33
Remainder = 1
(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
OUTPUT :-
((1, 2, 3, 4, 5, 6),)
Program :-
# an unnamed tuple of values assigned to values of another unnamed tuple
(val1, val2, val3) = (1,2,3)
print(val1, val2, val3)
Tup1 = (100,200,300)
(val1,val2,val3) = Tup1 # tuple assigned to another tuple
print(val1,val2,val3)
# expression are evaluated before assignment
(val1,val2,val3) = (2+4 ,5/3+4,9%6)
print(val1,val2,val3)
OUTPUT :-
123
100 200 300
6 5.666666666666667 3
OUTPUT :-
[(1, 'a'), (2, 'b'), (3, 'c'), (4, 'd'), (5, 'e')]
Aim :- write a python program on tuples for returning multiple values and nested
tuples.
Program :-
def max_min(vals):
x = max(vals)
y = min(vals)
return(x,y)
vals = (99,98,90,97,89,86,93,82)
(max_marks,min_marks) = max_min(vals)
print("Highest Marks = ",max_marks)
print("Lowest Marks = ",min_marks)
print("-------------------------------")
Toppers = (("Arav","BSc",92.0),("chaitanya","BCA",99.0),("Dhruvika","Btech",97))
for i in Toppers:
print(i)
OUTPUT :-
Highest Marks = 99
Lowest Marks = 82
-------------------------------
('Arav', 'BSc', 92.0)
('chaitanya', 'BCA', 99.0)
('Dhruvika', 'Btech', 97)
Aim :- write a python program to deleting the elements from the tuple.
program :-
#Deleting Elements in Tuple
Tup1 = (1,2,3,4,5)
del Tup1[3]
print(Tup1)
Tup1 = (1,2,3,4,5)
del Tup1
print(Tup1)
OUTPUT :-
Program :-
Tup = (1,2,3,4,5,6,7,8)
print(Tup.index(4))
students = ("bhavya","Era","Falguni","Huma")
index = students.index("Falguni")
print("Falguni is present at location :",index)
index = students.index("Isha")
print("Isha is present at location :",index)
OUTPUT :-
Program :-
tup = "abcdxxxabcdxxxabcdxxx"
print("x appers ",tup.count('x')," times in ",tup)
def double(T):
return ([i*2 for i in T])
Tup = 1,2,3,4,5
print("Original Tuple :",Tup)
print("double values:",double(Tup))
OUTPUT :-
x appers 9 times in abcdxxxabcdxxxabcdxxx
Original Tuple : (1, 2, 3, 4, 5)
double values: [2, 4, 6, 8, 10]
Dictionary:-
Aim :- write a python program to adding and modifying an item in a dictionary
Program :-
Dict = {'Roll_No' : '16/001','Name' : 'Arav','course':'Btech'}
print("Dict[ROll_NO] = ",Dict['Roll_No'])
print("Dict[NAME] = ",Dict['Name'])
print("Dict[COURSE] = ",Dict['course'])
Dict['Marks'] = 95 #new entry
print("Dict[MARKS] = ",Dict['Marks'])
OUTPUT :-
Dict[ROll_NO] = 16/001
Dict[NAME] = Arav
Dict[COURSE] = Btech
Dict[MARKS] = 95
Aim :- Write a python program built in dictionary functions and methods.
Program :-
#Built-in Dictionary Functions and Methods
Dict1= {'Roll_No': '16/001', 'Name': 'Arav', 'Course': 'BTech'}
print(len(Dict1))
print("------------------------------")
subjects = ['CSA','C++','DS','OS']
Marks=dict.fromkeys(subjects,-1)
print(Marks)
print("------------------------------")
Dict1 = {'Roll_No': '16/001', 'Name': 'Arav', 'Course': 'BTech'}
print(Dict1.get('Name'))
print("------------------------------")
OUTPUT:-
3
------------------------------
{'Roll_No': '16/001', 'Name': 'Arav', 'Course': 'BTech'}
------------------------------
{}
------------------------------
Dict2 : {'Roll_No': '16/001', 'Name': 'Arav', 'Course': 'BTech'}
Dict1 after modification: {'Roll_No': '16/001', 'Name': 'Arav', 'Course': 'BTech'}
Dict2 after modification: {'Roll_No': '16/001', 'Name': 'Saesha', 'Course': 'BTech'}
------------------------------
{'CSA': -1, 'C++': -1, 'DS': -1, 'OS': -1}
------------------------------
Arav
------------------------------
False
------------------------------
dict_items([('Roll_No', '16/001'), ('Name', 'Arav'), ('Course', 'BTech')])
------------------------------
dict_keys(['Roll_No', 'Name', 'Course'])
------------------------------
Arav has got marks = None
------------------------------
{'Roll_No': '16/001', 'Name': 'Arav', 'Course': 'BTech', 'Marks': 90, 'Grade': '0'}
------------------------------
dict_values(['16/001', 'Arav', 'BTech'])
------------------------------
Roll_No 16/001
Name Arav
Course BTech
------------------------------
True
False
Aim :- write a python program to deleting an item from the dictionary.
Program :-
#Deleting Items
Dict = {'Roll_No' : '16/001','Name' : 'Arav','course':'Btech'}
print("Name is: ",Dict.pop('Name')) #returns name
print("Dictionary after popping Name is :",Dict)
print("Marks is: ",Dict.pop('Marks',-1)) #returns default values
print("Dictionary after popping Marks is :",Dict)
print("Randomly popping any item : ",Dict.popitem())
print("Dictionary after random popping is :",Dict)
print("Aggregate is :",Dict.pop('Aggr')) #gegerates error
print("Dictionary after popping Aggregate is :",Dict)
OUTPUT :-
Name is: Arav
Dictionary after popping Name is : {'Roll_No': '16/001', 'course': 'Btech'}
Marks is: -1
Dictionary after popping Marks is : {'Roll_No': '16/001', 'course': 'Btech'}
Randomly popping any item : ('course', 'Btech')
Dictionary after random popping is : {'Roll_No': '16/001'}
Aim :- write a python program to modify the entry in dictionary.
Program :-
Dict = {'Roll_No' : '16/001','Name' : 'Arav','course':'Btech'}
print("Dict[ROll_NO] = ",Dict['Roll_No'])
print("Dict[NAME] = ",Dict['Name'])
print("Dict[COURSE] = ",Dict['course'])
Dict['Marks'] = 95 #new entry
print("Dict[MARKS] = ",Dict['Marks'])
Dict ['course'] = 'BCA'
print("Dict[COURSE] = ",Dict['course']) #entry updated
OUTPUT :-
Dict[ROll_NO] = 16/001
Dict[NAME] = Arav
Dict[COURSE] = Btech
Dict[MARKS] = 95
Dict[COURSE] = BCA
OUTPUT:-
Sneha is studying Btech
Mayank is studying BCA
Program :-
#Accessing Values
Dict ={'Roll_No' : '16/001','Name' : 'Arav','course':'Btech'}
print("Dict[ROll_NO] = ",Dict['Roll_No'])
print("Dict[NAME] = ",Dict['Name'])
print("Dict[COURSE] = ",Dict['course'])
OUTPUT:-
Dict[ROll_NO] = 16/001
Dict[NAME] = Arav
Dict[COURSE] = Btech
Program :-
#Nested Dictionaries
Students = {'Shiv' : {'CS':90,'DS':89,'CSA':92},
'Sadhvi':{'CS':91,'DS':87,'CSA':94},
'Krish' :{'CS':93,'DS':92,'CSA':88}}
for key,val in Students.items():
print(key,val)
OUTPUT :-
Shiv {'CS': 90, 'DS': 89, 'CSA': 92}
Sadhvi {'CS': 91, 'DS': 87, 'CSA': 94}
Krish {'CS': 93, 'DS': 92, 'CSA': 88}
Program :-
Dict = {'Roll_No' : '16/001','Name' : 'Arav','Course':'Btech'}
print(sorted(Dict.keys()))
OUTPUT :-
['Course', 'Name', 'Roll_No']
KEYS: Roll_No Name Course
VALUES : 16/001 Arav Btech
DICTIONARY : Roll_No 16/001 Name Arav Course Btech
Sets :-
Aim :- write a python program on sets
Program :-
#sets
s = {1,2.0,"abc"}
print(s)
set([1,2.0,'abc'])
#set operations
#s.update(t)
s = set([1,2,3,4,5])
t =set([6,7,8])
s.update(t)
print(s)
print("-------------------")
#s.add(x)
s = set([1,2,3,4,5])
s.add(6)
print(s)
print("-------------------")
#s.remove(x)
s =set([1,2,3,4,5])
s.remove(3)
print(s)
print("-------------------")
#s.discard(x)
s= set([1,2,3,4,5])
s.discard(3)
print(s)
print("-------------------")
#s.pop()
s = set([1,2,3,4,5])
s.pop()
print(s)
print("-------------------")
#s.clear()
s = set([1,2,3,4,5])
s.clear()
print(s)
OUTPUT :-
{1, 2.0, 'abc'}
{1, 2, 3, 4, 5, 6, 7, 8}
-------------------
{1, 2, 3, 4, 5, 6}
-------------------
{1, 2, 4, 5}
-------------------
{1, 2, 4, 5}
-------------------
{2, 3, 4, 5}
-------------------
Set()
ii)
# len(s)
s = set([1,2,3,4,5])
print(len(s))
print("--------------------")
# x is s
s = set([1,2,3,4,5])
print(3 in s)
print("--------------------")
# x not in s
s = set([1,2,3,4,5])
print(6 not in s)
print("--------------------")
#s.issubset(t) or s<=t
s = set([1,2,3,4,5])
t = set([1,2,3,4,5,6,7,8,9,10])
print(s<=t)
print("--------------------")
# s.issuperset(t)
s= set([1,2,3,4,5])
t = set([1,2,3,4,5,6,7,8,9,10])
print(s.issuperset(t))
print("--------------------")
#s.union(t)
s= set([1,2,3,4,5])
t = set([1,2,3,4,5,6,7,8,9,10])
print(s|t)
print("--------------------")
#s.intersection(t)
s= set([1,2,3,4,5])
t = set([1,2,3,4,5,6,7,8,9,10])
z = s&t
print(z)
print("--------------------")
#s.intersection_update(t)
s = set([1,2,10,12])
t= set([1,2,3,4,5,6,7,8,9,10])
s.intersection_update(t)
print(s)
print("--------------------")
OUTPUT :-
5
--------------------
True
--------------------
True
--------------------
True
--------------------
False
--------------------
{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
--------------------
{1, 2, 3, 4, 5}
--------------------
{1, 2, 10}
--------------------
)
#set opertations
#s.difference(t)
s = set([1, 2, 10, 12])
t = set([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
z=s-t
print(z)
#s.difference_update(t)
s = set([1,2,10,12])
t = set([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
s.difference_update(t)
print(s)
#s.symmetric_difference(t) or s^t
s = set([1,2,10,12])
t = set([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
z=s^t
print(z)
#s.copy
s = set([1,2,10,12])
t = set([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
print(s.copy())
#s.isdisjoint(t)
set([1, 2, 3])
t = set([4, 5, 6])
print(s.isdisjoint(t))
#all(s)
s = set([0, 1, 2, 3, 4])
print(all(s))
#any(s)
s = set([0, 1, 2, 3, 4])
print(any(s))
OUTPUT :-
{12}
{12}
{3, 4, 5, 6, 7, 8, 9, 12}
{1, 2, 10, 12}
True
False
True
iv)
### 1. Enumerate a Set
s = set(['a', 'b', 'c', 'd'])
for i in enumerate(s):
print(i, end=' ')
print("\n------------------------\n")
s = set([0, 1, 2, 3, 4, 5])
print(min(s))
print("------------------------")
print(s == t)
print(s != z)
OUTPUT :-
(0, 'd') (1, 'c') (2, 'b') (3, 'a')
------------------------
5
------------------------
0
------------------------
15
------------------------
[0, 1, 2, 3, 4, 5]
------------------------
True
False
Aim :- Write a python program to define class and object for real world occurance
Program :-
class Dog:
a = "mammal"
b = "dog"
def fun(self):
print("I'm a", self.a)
print("I'm a", self.b)
OUTPUT :-
mammal
I'm a mammal
I'm a dog
Aim :- write a python program based on constructors using self.
Program :-
class User:
def __init__(self, name, age, gender):
self.name = name
self.age = age
self.gender = gender
def get_details(self):
print("Personal Details:")
print("\tName:", self.name)
print("\tAge:", self.age)
print("\tGender:", self.gender)
OUTPUT :-
Personal Details:
Name: manoj
Age: 18
Gender: male
Aim :- write a python program to print the dictionaries in different ways and modify
values and adding new keys.
Program :-
d1 = {}
d2 = {1:'a',2:'b',3:'c'}
d3= {'a':'Hello','b':[1,2,3],'c':3}
d4 = dict([('a',10),('b',20)])
d5 = {1:'a',2:{'b':'two','c':'three'},3:'d'}
print(d1)
print(d2)
print(d3)
print(d4)
print(d5)
OUTPUT:-
{}
{1: 'a', 2: 'b', 3: 'c'}
{'a': 'Hello', 'b': [1, 2, 3], 'c': 3}
{'a': 10, 'b': 20}
{1: 'a', 2: {'b': 'two', 'c': 'three'}, 3: 'd'}
Aim :- write a python program to handle exceptions using try and expect.
Program :-
def divide(x, y):
try:
result = x // y
print("Yeah! Your answer is:", result)
except ZeroDivisionError:
print("Sorry! You are dividing by zero.")
divide(3, 0)
OUTPUT :-
Sorry! You are dividing by zero.
Program :-
class Parent:
def fun1(self):
print("This function is in the parent class.")
class Child1(Parent):
def fun2(self):
print("This function is in child1.")
class Child2(Parent):
def fun3(self):
print("This function is in child2.")
Program :-
# Multilevel Inheritance
class Base:
def __init__(self, Basename):
self.Basename = Basename
class derived1(Base):
def __init__(self, derivedname, Basename):
self.derivedname = derivedname
Base.__init__(self, Basename)
class Son(derived1):
def __init__(self, sonname, derivedname, Basename):
self.sonname = sonname
derived1.__init__(self, derivedname, Basename)
def print_name(self):
print("Base name:", self.Basename)
print("Derived name:", self.derivedname)
print("Son name:", self.sonname)
s1 = Son("Prince", "Rampal", "Lalmani")
print(s1.Basename)
s1.print_name()
OUTPUT :-
Lalmani
Base name: Lalmani
Derived name: Rampal
Son name: Prince
Program :-
class Mother:
mothername = ""
def mother(self):
print(self.mothername)
class Father:
fathername = ""
def father(self):
print(self.fathername)
OUTPUT :-
Father: Prakash
Mother: Krishnaveni
Aim :- write a python program to remove the duplicates from a given string.
Program :-
s = input()
ans = ''
l = [0] * 26
for i in s:
if l[ord(i) - 97] == 0: # Check if the character hasn't been added
ans += i
l[ord(i) - 97] += 1
print(ans)
OUTPUT :-
pythonprogramming
pythonrgami
class Child(Parent):
def fun2(self):
print("This function is in the child class.")
OUTPUT :-
This function is in the parent class.
This function is in the child class.