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

python record(AIML)

Uploaded by

Kandula Anusha
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
25 views

python record(AIML)

Uploaded by

Kandula Anusha
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 64

Python Lab Manual

Department of CSE – AIML


II- YEAR

Aim :- write a python program to find the number is even or odd.


Program :-
#input from user
number = int(input("enter the number"))
# check if the number is even or odd
if number % 2 == 0:
print(f"{number} is even")
else:
print(f"{number} is odd")
OUTPUT :-
enter the number 1000
1000 is even
Enter the number 675
675 is odd

Aim:- write a python program to print the Fibonacci series.

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]

Aim :- Write a python program to find largest of three numbers.


Program :-

# Taking three inputs from the user

number1 = int(input("enter the first number"))


number2 = int(input("enter the second number"))
number3 = int(input("enter the third number"))

# by using if statement we have to check the largest of three numbers

if number1 > number2 and number1 > number3:


largest = number1

elif number2 > number3:


largest = number2

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:-

enter the number :-153


the given number is armstrong number

enter the number :- 345


the given number is not armstrong number

Aim :- Write a python program to find the factorial of a given number ?


Program :-
# Input from user
number = int(input("Enter a number: "))
# Initialize factorial to 1
factorial = 1
# Calculate factorial using a loop
if number < 0:
print("Factorial is not defined for negative numbers.")
elif number == 0:
print("Factorial of 0 is 1.")
else:
for i in range(1, number + 1):
factorial *= i
print("Factorial of", number, "is", factorial)

OUTPUT :-
1).Enter a number: 5
Factorial of 5 is 120

2).Enter a number: -3
Factorial is not defined for negative numbers.

Aim :- Write a python program to findpalindrome or not ?

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 print the multiplication table.


Program :-
#input is taken from the user
num=int(input("enter the number"))
for i in range(1,11):
print(f"{num} * {i} = {num*i}")
OUTPUT:-
enter the number 5
5*1=5
5 * 2 = 10
5 * 3 = 15
5 * 4 = 20
5 * 5 = 25
5 * 6 = 30
5 * 7 = 35
5 * 8 = 40
5 * 9 = 45
5 * 10 = 50

Aim :- write a python program to print prime numbers from 1 to 100


Program :-
#input is taken by user
a = int(input("enter the starting number"))
b = int(input("enter the starting number"))
for i in range(a,b+1):
is_prime = True
for j in range (2,i):
if i%j == 0:
is_prime = False
break
if is_prime:
print(i)
OUTPUT:-

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

2) enter the number 3


3 is 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

Aim :- Demonstrate the following operators in python.


Program :-

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

print('*****2. Comparison Operators*****\n')


# Equal to
x = (5 == 5) # True
# Not equal to
y = (5 != 3) # True
# Greater than
z = (7 > 5) # True
# Less than
a = (3 < 5) # True
# Greater than or equal to
b = (5 >= 5) # True
# Less than or equal to
c = (3 <= 4) # True
print(f" x = {x}, y = {y}, z = {z}, a = {a}, b = {b}, c = {c}\n")
print("*****3. Logical Operators******\n")
# Logical AND
x = (5 > 3 and 8 > 5) # True
# Logical OR
y = (5 > 3 or 8 < 5) # True
# Logical NOT
z = not (5 > 3) # False
print(f" x = {x} , y = {y}, z = {z}\n")

print('******4. Assignment Operators******\n')


# Assign
x = 10
# Add and assign
x += 5 # x becomes 15
print(x)
# Subtract and assign
x -= 3 # x becomes 12
print(x)
# Multiply and assign
x *= 2 # x becomes 24
print(x)
# Divide and assign
x /= 4 # x becomes 6.0
# Floor divide and assign
x //= 2 # x becomes 3.0
print(x)
# Modulus and assign
x %= 2 # x becomes 1.0
print(x)
# Exponentiate and assign
x **= 3 # x becomes 1.0
print(x)

print('******5. Bitwise Operators******\n')


# Bitwise AND
a=5&3 # 1 (0101 & 0011)

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

print('******6. Membership Operators******\n')


# In
x = 3 in [1, 2, 3] # True
# Not in
y = 4 not in [1, 2, 3] # True
print(f" x = {x} , y = {y}")

print('*******7. Identity Operators ********')

# Is
a = (5 is 5) # True

# Is not
b = (5 is not 3) # True
print(f" a = {a} ,b = {b}\n")

print('*******8. Conditional Expressions (Ternary Operator)*********\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

*****2. Comparison Operators*****

x = True, y = True, z = True, a = True, b = True, c = True

*****3. Logical Operators******

x = True , y = True, z = False

******4. Assignment Operators******

15
12
24
3.0
1.0
1.0
******5. Bitwise Operators******

a = 1, b = 7, c = 6, d = -6, e = 10, f = 2

******6. Membership Operators******

x = True , y = True
*******7. Identity Operators ********
a = True ,b = True

*******8. Conditional Expressions (Ternary Operator)*********

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

# Check if the number is negative


if num < 0:
print("Factorial does not exist for negative numbers.")
else:
print(f"Factorial of {num} is {factorial(num)}")
OUTPUT :-
Enter a number: 24
Factorial of 24 is 620448401733239439360000
Aim :- Write a python program to differentiate between arguments and
Keyword arguments.
Program :-
def args_kwargs(*args, **kwargs):
print("Positional arguments (args):")
for arg in args:
print(arg)
print("\nKeyword arguments (kwargs):")
for key, value in kwargs.items():
print(f"{key}: {value}")

# Calling the function with both positional and keyword argument


args_kwargs(1, 2, 3, name="Alice", age=30)

OUTPUT :-
Positional arguments (args):
1
2
3
Keyword arguments (kwargs):
name: Alice
age: 30

Aim :- Write a python program to check whether numberfalls with in a specified


range .
program :-
def is_in_range(number, start, end):
if start <= number <= end:
return True
else:
return False
# Input from the user
num = int(input("Enter a number: "))
range_start = int(input("Enter the start of the range: "))
range_end = int(input("Enter the end of the range: "))

# Check if the number is within the range


if is_in_range(num, range_start, range_end):
print(f"{num} is within the range {range_start} to {range_end}.")
else:
print(f"{num} is not within the range {range_start} to {range_end}.")
OUTPUT :-
1) Enter a number: 6
Enter the start of the range: 1
Enter the end of the range: 10
6 is within the range 1 to 10.

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

Aim :- Write a python program to find maximum frequency of a letter.


Program :-
def max_frequency(string):
# Create a dictionary to store the frequency of each character
frequency = {}
for char in string:
if char in frequency:
frequency[char] += 1
else:
frequency[char] = 1
# Find the character with the maximum frequency
max_char = max(frequency, key=frequency.get)
return max_char, frequency[max_char]
# Taking input from the user
string = input("Enter a string: ")
char, freq = max_frequency(string)
print(f"The character '{char}' appears {freq} times, which is the maximum frequency.")

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

Aim :- write a python program to split and join a string.


Program :-
def split_join(sentence):
words = sentence.split()
join_sentence = ' ,'.join(words)
return join_sentence
sentence = input("enter a sentence:")
result = split_join(sentence)
print("joined strinng ",result)

OUTPUT :-
enter a sentence: python programming
joined string python-programming

Aim :- write a python program to count no. of vowels in a string.


Program:-
string = input("Enter a string: ")
# Count the number of vowels
count = sum(1 for char in string if char.lower() in 'aeiou')
print("Number of vowels:",count)
OUTPUT :-
Enter a string: python programming
Number of vowels: 4

Aim :- Write a python program to remove white spaces.


Program :-
# Input: Get a string from the user
input_string = input("Enter a string: ")

# Remove whitespace characters


output_string = input_string.replace(" ", "")

# Print the modified string


print("String after removing whitespace:", output_string)
OUTPUT :-
Enter a string: vignans nirula
String after removing whitespace: vignansnirula

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

2) Enter a string: 35676 python


The string does not start with alphabet.
Number of other characters: 1

Aim :- write a python program to print evenlength words.


Program :-
def even_length(sentence):
words = sentence.split()
for word in words:
if len(word)%2 == 0:
print(word)
sentence = input("enter the string:")
even_length(sentence)
OUTPUT :-
enter the string: The program is about to print even length words
is
to
even
length
Aim :- write a python program to print first half in upper case and next half in lower
case .
Program :-
def input_string(word):
middle = len(word)//2
firsthalf = word[:middle].upper()
secondhalf = word[middle:].lower()
return firsthalf + secondhalf
word = input("enter a word:")
input_word = input_string(word)
print("formatted word :",input_word)
OUTPUT :-
enter a word : python programming
formatted word : PYTHON Programming
Aim :- write a python program to capitalize the alternative characters of a given string
Program :-
string = input("Enter a string: ") # Input taken from the user
capitilesd_str = '' # Capitalize alternative characters
for i in range(len(string)):
if i % 2 == 0:
capitilesd_str += string[i].upper()
else:
capitilesd_str += string[i]
# print the capatilized string
print("String with alternative characters capitalized:",capitilesd_str)

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

Aim :- Write a python to program to square the numbers of a list.


Program :-
numbers = list(map(int, input("Enter numbers separated by spaces: ").split()))
squarenumbers = [x ** 2 for x in numbers]
print("Squared elements in reverse order:", squarenumbers[::-1])

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

num = list(map(int, input("Enter numbers separated by spaces: ").split()))


largest, smallest = largest_smallest(num)
print(f"Largest number is: {largest} and Smallest number is: {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]

Aim :- write a pythonprogram to remove negative values in the list.

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]

Aim :- Write a python program to remove spaces from a given list.

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

Aim :- write a python program to split the lists.

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]

# Count even and odd numbers


even = len(even_num)
odd = len(odd_num)
# Print the results
print("Even numbers:", even_num)
print("Count of even numbers:",even)
print("Odd numbers:", odd_num)
print("Count of odd numbers:",odd)

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)

Aim :-Write a python program on the utility of tuples.


Program :-
#Utility of Tuples
quo ,rem = divmod(100,3)
print("quotient = ",quo)
print("Remainder = ",rem)

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)

Aim :- write a python program on Variable-length Argument Tuples.


Program :-
def display(*args):
print(args)
Tup = (1,2,3,4,5,6)
display(Tup)

OUTPUT :-
((1, 2, 3, 4, 5, 6),)

Aim :- write a python program on the tuple assignment.

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

Aim :- write a python program on zip () method.


Program :-
#The zip() Function
Tup = (1,2,3,4,5)
list1 = ['a','b','c','d','e']
print(list((zip(Tup,list1))))

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 :-

Aim :- write a python program to check the index

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 :-

Aim :- Write a python program to Checking the Index: index() method

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("------------------------------")

Dict1 = {'Roll_No': '16/001', 'Name': 'Arav', 'Course': 'BTech'}


print(str(Dict1))
print("------------------------------")

Dict1 = {'Roll_No': '16/001', 'Name': 'Arav', 'Course': 'BTech'}


Dict1.clear()
print(Dict1)
print("------------------------------")

Dict1 = {'Roll_No': '16/001', 'Name': 'Arav', 'Course': 'BTech'}


Dict2 = Dict1.copy()
print("Dict2 :",Dict2)
Dict2['Name'] = 'Saesha'
print("Dict1 after modification:",Dict1)
print("Dict2 after modification:",Dict2)
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("------------------------------")

Dict1 = {'Roll_No': '16/001', 'Name': 'Arav', 'Course': 'BTech'}


print('Marks' in Dict1)
print("------------------------------")

Dict1 = {'Roll_No': '16/001', 'Name': 'Arav', 'Course': 'BTech'}


print(Dict1.items())
print("------------------------------")

Dict1 = {'Roll_No': '16/001', 'Name': 'Arav', 'Course': 'BTech'}


print(Dict1.keys())
print("------------------------------")

Dict1 = {'Roll_No': '16/001', 'Name': 'Arav', 'Course': 'BTech'}


Dict1.setdefault('Marks',0)
print(Dict1['Name'],"has got marks = ",Dict1.get('marks'))
print("------------------------------")

Dict1 = {'Roll_No': '16/001', 'Name': 'Arav', 'Course': 'BTech'}


Dict2 = {'Marks' : 90,'Grade': '0'}
Dict1.update(Dict2)
print(Dict1)
print("------------------------------")

Dict1 = {'Roll_No': '16/001', 'Name': 'Arav', 'Course': 'BTech'}


print(Dict1.values())
print("------------------------------")

Dict = {'Roll_No': '16/001', 'Name': 'Arav', 'Course': 'BTech'}


for i,j in Dict.items():
print(i, j)
print("------------------------------")

Dict = {'Roll_No': '16/001', 'Name': 'Arav', 'Course': 'BTech'}


print('Name' in Dict)
print('Marks' in Dict)

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

Aim :- Write a python program in string formatting in dictionaries.


Program :-
#String Formatting with Dictionaries
Dict = {'Sneha': 'Btech', 'Mayank' : 'BCA'}
for key,val in Dict.items():
print("%s is studying %s" %(key,val))

OUTPUT:-
Sneha is studying Btech
Mayank is studying BCA

Aim :- write a python program to access the values in the dictionary.

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

Aim :- write a python program based on the Nested Dictionaries.

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}

Aim :- write a python program to sort the items in a dictionary.

Program :-
Dict = {'Roll_No' : '16/001','Name' : 'Arav','Course':'Btech'}
print(sorted(Dict.keys()))

Dict = {'Roll_No':'16/001','Name' : 'Arav' ,'Course': 'Btech'}


print("KEYS: ",end = ' ')
for key in Dict:
print(key,end = ' ') #accecssing only keys
print("\nVALUES : ", end = ' ')
for val in Dict.values():
print(val,end=' ') # accessing only values
print("\nDICTIONARY :",end = ' ')
for key, val in Dict.items():
print(key,val,"\t",end = ' ')#accessing keys and values

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

### 2. Maximum Value in a Set


s = set([0, 1, 2, 3, 4, 5])
print(max(s))
print("------------------------")

### 3. Minimum Value in a Set

s = set([0, 1, 2, 3, 4, 5])
print(min(s))
print("------------------------")

### 4. Sum of Elements in a Set


s = set([0, 1, 2, 3, 4, 5])
print(sum(s))
print("------------------------")

### 5. Sorted List from a Set


s = set([5, 4, 3, 2, 1, 0])
print(sorted(s))
print("------------------------")

### 6. Set Equivalence Check


s = set(['a', 'b', 'c'])
t = set('abc')
z = set(tuple('abc'))

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)

# Creating an instance of Dog


rodger = Dog()
print(rodger.a)
rodger.fun()

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)

# Creating an instance of User


s = User("manoj", 18, 'male')
s.get_details()

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.

Aim :- write a python program based on the hierarchial inheritance .

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.")

# Creating instances of Child1 and Child2


o1 = Child1()
o2 = Child2()

# Calling functions from the parent and child classes


o1.fun1()
o1.fun2()
o2.fun1()
o2.fun3()
OUPUT :-
This function is in the parent class.
This function is in child1.
This function is in the parent class.
This function is in child2.

Aim :- write a python program based on multilevel inheritance.

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

Aim :- write a python program based on the multiple inheritance.

Program :-
class Mother:
mothername = ""
def mother(self):
print(self.mothername)
class Father:
fathername = ""
def father(self):
print(self.fathername)

class Son(Father, Mother):


def parents(self):
print("Father:", self.fathername)
print("Mother:", self.mothername)

# Creating an instance of Son


s1 = Son()
s1.fathername = 'Prakash'
s1.mothername = 'Krishnaveni'
s1.parents()

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

Aim :- Write a python program based on types of inheritance


Program :-
class Parent:
def fun1(self):
print("This function is in the parent class.")

class Child(Parent):
def fun2(self):
print("This function is in the child class.")

# Creating an instance of Child


o1 = Child()
o1.fun1() # Calling fun1() from the parent class
o1.fun2() # Calling fun2() from the child class

OUTPUT :-
This function is in the parent class.
This function is in the child class.

You might also like