0% found this document useful (0 votes)
26 views30 pages

20IT425 Python

Uploaded by

fact
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)
26 views30 pages

20IT425 Python

Uploaded by

fact
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/ 30

4IT01: Python Programming

Practical 1 – Basics of Python


1.1 WAP to calculate Area and parameter of the square.

def are(len):
return len*len

def parameter(len):
return 4*len

a = int(input("Enter length of square"))

print("Area of Square : ",are(a))


print("Parameter of Square : ",parameter(a))

Output:

1.2 WAP to swap of two variables.


def swap_variables(a, b):
print("Before swapping:")
print("a =", a)
print("b =", b)
# Swapping the values
temp = a
a=b
b = temp
print("After swapping:")
print("a =", a)
print("b =", b)
x = 10
y = 20
swap_variables(x, y)

20IT425 1
4IT01: Python Programming

Output:

1.3 WAP to find out absolute value of an input number take input from user.

def find_absolute_value(number):
if number < 0:
number = -number
return number

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

absolute_value = find_absolute_value(num)

print("The absolute value of", num, "is", absolute_value)

Output:

1.4 WAP to show the eval function.


expression = input("Enter an expression: ")
result = eval(expression)
print("Result:", result)
print(type(result))

Output:

20IT425 2
4IT01: Python Programming

1.5 WAP to convert days into months and days.


def convert_days_to_months_and_days(days):
months = days // 30
remaining_days = days % 30
return months, remaining_days
days = int(input("Enter the number of days: "))
months, remaining_days = convert_days_to_months_and_days(days)
print(days, "days is equal to", months, "months and", remaining_days, "days.")

Output:

1.6 WAP to convert bits to Gigabyte, Megabyte and Terabyte.

def convert_bits(bits):
# Constants for conversion
gigabyte = bits / (8 * 1024 ** 3)
megabyte = bits / (8 * 1024 ** 2)
terabyte = bits / (8 * 1024 ** 4)
return gigabyte, megabyte, terabyte
bits = float(input("Enter the number of bits: "))
gigabyte, megabyte, terabyte = convert_bits(bits)

print(bits, "bits is equal to:")


print("Gigabytes:", gigabyte)
print("Megabytes:", megabyte)
print("Terabytes:", terabyte)

Output:

20IT425 3
4IT01: Python Programming

20IT425 4
4IT01: Python Programming

Practical 2 – If…else and elif


2.1 WAP to check given number is odd or even.

def odd_even(no):
if(no%2==0):
print("Even")
else:
print("Odd")

number = eval(input("Enter any number"))

odd_even(number)

Output:

2.2 WAP to check if input year is leap year or not.

def is_leap_year(year):
if year % 4 == 0:
if year % 100 == 0:
if year % 400 == 0:
return True
else:
return False
else:
return True
else:
return False

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

if is_leap_year(year):
print(year, "is a leap year.")
else:
print(year, "is not a leap year.")

20IT425 5
4IT01: Python Programming

Output:

2.3 WAP to check number is postive, negative or zero.


def pos_neg_zero(number):
if(number<0):
print("Negative")
elif(number==0):
print("Zero")
else:
print("Positive")
number = eval(input("Enter any number "))
pos_neg_zero(number)

Output:

2.4 WAP a program that takes the mark of 5 subject and displat the the grade.

def calculate_grade(average_mark):
if average_mark >= 90:
return "A+"
elif average_mark >= 80:
return "A"
elif average_mark >= 70:
return "B"
elif average_mark >= 60:
return "C"
elif average_mark >= 50:
return "D"
else:

20IT425 6
4IT01: Python Programming

return "F"

marks = []
for i in range(5):
subject_mark = float(input("Enter the mark for subject {}: ".format(i+1)))
marks.append(subject_mark)

average = sum(marks) / len(marks)

grade = calculate_grade(average)

print("Average Mark:", average)


print("Grade:", grade)

Output:

20IT425 7
4IT01: Python Programming

20IT425 8
4IT01: Python Programming

Practical 3 – Loops
3.1 WAP to print all even number between 1 to 100 using while loop.

number = 1

while number <= 100:


if number % 2 == 0:
print(number)
number += 1

Output:

3.2 WAP to calculate factorial of given number.

def fact(num):
f=1

while(num>0):
f=f*num
num-=1
return f

num = eval(input("Enter any number to find factorial for the same : "))

fact(num)

Output:

20IT425 9
4IT01: Python Programming

3.3 WAP to takes number and find sum of digits from that number.

num = eval(input("Enter any number : "))


s=0
while(num>0):
s+=num%10
num//=10
print("Sum of digits of given number is : ",s)

Output:

3.4 WAP to print bottom to top pyramid for *.

def print_bottom_to_top_pyramid(rows):
for i in range(rows, 0, -1):
print(" " * (rows - i) + "*" * (2 * i - 1))

num_rows = int(input("Enter the number of rows: "))

print_bottom_to_top_pyramid(num_rows)

Output:

20IT425 10
4IT01: Python Programming

Practical 4 – Tuple, List and Dictionaries


4.1 WAP to find min and max value from list of tuples.

def find_min_max_from_tuples(lst):
if not lst:
return None, None

min_val = max_val = lst[0][0]

for tuple_elem in lst:


for value in tuple_elem:
if value < min_val:
min_val = value
if value > max_val:
max_val = value

return min_val, max_val

tuples_list = [(3, 8), (1, 5), (7, 2), (6, 4)]


min_val, max_val = find_min_max_from_tuples(tuples_list)
print("Minimum value:", min_val)
print("Maximum value:", max_val)

Output:

4.2 WAP to find the repeated items of a tuple.

def find_repeated_items_in_tuple(tup):
repeated_items = []
seen_items = set()

for item in tup:


if item in seen_items and item not in repeated_items:
repeated_items.append(item)
else:
seen_items.add(item)

20IT425 11
4IT01: Python Programming

return repeated_items

my_tuple = (1, 2, 3, 2, 4, 5, 4, 6, 7, 8, 5)
repeated_items = find_repeated_items_in_tuple(my_tuple)
print("Repeated items:", repeated_items)

Output:

4.3 WAP to sum all the items in a list.

def sum_list_items(lst):
total_sum = 0

for item in lst:


total_sum += item

return total_sum

my_list = [1, 2, 3, 4, 5]
result = sum_list_items(my_list)
print("Sum of list items:", result)

Output:

4.4 WAP to Find the Union of Two Lists.

def find_union_of_lists(list1, list2):


union_set = set(list1).union(list2)
return list(union_set)

list1 = [1, 2, 3, 4, 5]
list2 = [4, 5, 6, 7, 8]
result_union = find_union_of_lists(list1, list2)
print("Union of lists:", result_union)

20IT425 12
4IT01: Python Programming

Output:

4.5 WAP to Print Smallest Even and Smallest Odd Number in a List.

def find_smallest_even_odd(lst):
smallest_even = None
smallest_odd = None

for num in lst:


if num % 2 == 0:
if smallest_even is None or num < smallest_even:
smallest_even = num
else:
if smallest_odd is None or num < smallest_odd:
smallest_odd = num

return smallest_even, smallest_odd

my_list = [5, 3, 2, 7, 8, 4, 9, 1, 6]
smallest_even, smallest_odd = find_smallest_even_odd(my_list)

if smallest_even is not None:


print("Smallest even number:", smallest_even)
else:
print("No even numbers in the list.")

if smallest_odd is not None:


print("Smallest odd number:", smallest_odd)
else:
print("No odd numbers in the list.")

Output:

20IT425 13
4IT01: Python Programming

4.6 WAP to find common items from two lists.

def find_common(lst1,lst2):
dct={}
lst3=[]
for i in lst1:
dct[i] = 1

for i in lst2:
if i in dct and dct[i]==1:
lst3.append(i)

print("Common item in both list : ",lst3)

list1 = [1, 2, 3, 4, 5]
list2 = [4, 5, 6, 7, 8]

find_common(list1,list2)

Output:

4.7 WAP to combine two dictionary adding value of a common key.

def combine_dicts(dict1, dict2):


combined_dict = dict1.copy()

for key, value in dict2.items():


if key in combined_dict:
combined_dict[key] += value
else:
combined_dict[key] = value

return combined_dict

dict1 = {'a': 10, 'b': 20, 'c': 30}


dict2 = {'b': 5, 'c': 15, 'd': 25}
result_dict = combine_dicts(dict1, dict2)
print("Combined dictionary:", result_dict)

20IT425 14
4IT01: Python Programming

Output:

4.8 WAP to Multiply All the Items in a Dictionary.

def multiply_all_items(dictionary):
result = 1

for value in dictionary.values():


result *= value

return result

my_dict = {'a': 2, 'b': 3, 'c': 4}


result = multiply_all_items(my_dict)
print("Result of multiplying all items:", result)

Output:

4.9 WAP to Sort Dictionaries by value.

def sort_dict_by_value(dictionary):
sorted_dict = dict(sorted(dictionary.items(), key=lambda item: item[1]))
return sorted_dict

my_dict = {'a': 3, 'b': 1, 'c': 5, 'd': 2}


sorted_dict = sort_dict_by_value(my_dict)
print("Sorted dictionary by value:", sorted_dict)

Output:

20IT425 15
4IT01: Python Programming

WAP to find the highest 3 values in a dictionary.

def find_highest_3_values(dictionary):
sorted_items = sorted(dictionary.items(), key=lambda item: item[1], reverse=True)
highest_3_values = sorted_items[:3]
return highest_3_values

my_dict = {'a': 10, 'b': 30, 'c': 20, 'd': 50, 'e': 40}
highest_3_values = find_highest_3_values(my_dict)
print("Highest 3 values in the dictionary:", highest_3_values)

Output:

20IT425 16
4IT01: Python Programming

Practical 5 – String
5.1 WAP to remove left and right-hand side space form the string.

def remove_right_space(str):
st = str.rstrip()

return st

str = eval(input("Enter your string : "))

print("after removing right space new string is : ",remove_right_space(str))

Output:

5.2 WAP to remove duplicate character from a String.

def remove_duplicates(input_str):
seen_chars = set()
result_str = ''

for char in input_str:


if char not in seen_chars:
result_str += char
seen_chars.add(char)

return result_str

input_string = "hello this is best place for learning more"


result = remove_duplicates(input_string)
print("String with duplicate characters removed:", result)

Output:

20IT425 17
4IT01: Python Programming

5.3 WAP to check string starts and end with specific value.

def check_start_end(input_str, start_value, end_value):


starts_with_specific_value = input_str.startswith(start_value)
ends_with_specific_value = input_str.endswith(end_value)

return starts_with_specific_value, ends_with_specific_value

my_string = "Hello, how are you?"


start_value = "Hello"
end_value = "you?"
starts_with, ends_with = check_start_end(my_string, start_value, end_value)

print("Starts with specific value:", starts_with)


print("Ends with specific value:", ends_with)

Output:

5.4 WAP to reverse a given String without using function.

def reverse_string(str):
st = str[::-1]

return st

str1 = eval(input("Enter your string here for reversing that : "))

print("Result as reverse string is : ",reverse_string(str1))

Output:

20IT425 18
4IT01: Python Programming

5.5 WAP to count available space in the given text.

def count_space(str):
c=0
for i in str:
if i!=' ':
c+=1

return c

str1 = eval(input("Enter your string here for count space : "))

print("number of space in given string is : ",count_space(str1))

Output:

20IT425 19
4IT01: Python Programming

20IT425 20
4IT01: Python Programming

Practical 6 – Functions
6.1 WAP to create a function that takes a number as a parameter and check the number is
prime or not.
def is_prime(number):
if number <= 1:
return False
for i in range(2, int(number ** 0.5) + 1):
if number % i == 0:
return False
return True
num = int(input("Enter number for finding prime or not : "))
if is_prime(num):
print(f"{num} is a prime number.")
else:
print(f"{num} is not a prime number.")

Output:

20IT425 21
4IT01: Python Programming

6.2 WAP to add two strings using a function.


def concat_two_string(str1,str2):
str3 = str1+str2
return str3
st1 = eval(input("Enter string-1 : "))
st2 = eval(input("Enter string-2 : "))
print("After combining two string resultant string is : ",concat_two_string(st1,st2))

Output:

6.3 WAP to calculate total upper case and lower case letter of a given string.
def count_upper_lower(str):
upper_c=0
lower_c=0
for i in str:
if i.isupper():
upper_c+=1
if i.islower():
lower_c+=1
return upper_c,lower_c
st = eval(input("Enter any string for finding upper and lower from it : "))
print("No of upper and lower char respectively ",count_upper_lower(st))

20IT425 22
4IT01: Python Programming

Output:

6.4 WAP to arrange given number in descending orders import module of ascending order.
def arrange_in_descending(numbers_list):
sorted_numbers_descending = sorted(numbers_list, reverse=True)
return sorted_numbers_descending

numbers = [10, 5, 8, 3, 7, 2]
sorted_descending = arrange_in_descending(numbers)
print("Numbers in descending order:", sorted_descending)

Output:

20IT425 23
4IT01: Python Programming

20IT425 24
4IT01: Python Programming

Practical 7 – OOP
7.1 WAP to add complex number using class and object.
class ComplexNumber:
def __init__(self, real, imaginary):
self.real = real
self.imaginary = imaginary
def add(self, other):
new_real = self.real + other.real
new_imaginary = self.imaginary + other.imaginary
return ComplexNumber(new_real, new_imaginary)
def __str__(self):
if self.imaginary >= 0:
return f"{self.real} + {self.imaginary}i"
else:
return f"{self.real} - {abs(self.imaginary)}i"
if __name__ == "__main__":
complex1 = ComplexNumber(3, 2)
complex2 = ComplexNumber(1, -4)
result = complex1.add(complex2)
print("Complex Number 1:", complex1)
print("Complex Number 2:", complex2)
print("Sum:", result)

Output:

20IT425 25
4IT01: Python Programming

7.2 WAP to check string is palindrome or not using class.


class PalindromeChecker:
def __init__(self, string):
self.string = string
def is_palindrome(self):
cleaned_string = ''.join(char.lower() for char in self.string if char.isalnum())
return cleaned_string == cleaned_string[::-1]
if __name__ == "__main__":
user_input = input("Enter a string: ")
palindrome_checker = PalindromeChecker(user_input)
if palindrome_checker.is_palindrome():
print("The string is a palindrome.")
else:
print("The string is not a palindrome.")

Output:

20IT425 26
4IT01: Python Programming

7.3 WAP multiply the positive numbers using multiple inheritance.


class PositiveNumberMultiplier:
def multiply_positive_numbers(self, num_list):
result = 1
for num in num_list:
if num > 0:
result *= num
return result

class InputHandler:
def get_positive_numbers(self):
num_list = []
while True:
try:
num = int(input("Enter a positive number (or 0 to stop): "))
if num < 0:
print("Please enter a positive number.")
elif num == 0:
break
else:
num_list.append(num)
except ValueError:
print("Invalid input. Please enter a valid number.")
return num_list

class PositiveNumberMultiplierApp(PositiveNumberMultiplier, InputHandler):


def run(self):
num_list = self.get_positive_numbers()

20IT425 27
4IT01: Python Programming

if num_list:
result = self.multiply_positive_numbers(num_list)
print("Result:", result)
else:
print("No positive numbers entered.")

if __name__ == "__main__":
app = PositiveNumberMultiplierApp()
app.run()

Output:

20IT425 28
4IT01: Python Programming

7.4 WAP to create employee salary system for PF, TDS and 80C.
class EmployeeSalarySystem:
def __init__(self, name, basic_salary, hra, medical_allowance, other_allowance,
investments_80c):
self.name = name
self.basic_salary = basic_salary
self.hra = hra
self.medical_allowance = medical_allowance
self.other_allowance = other_allowance
self.investments_80c = investments_80c

def calculate_pf(self):
pf_rate = 0.12 # Assuming 12% of basic salary for PF deduction
pf_deduction = self.basic_salary * pf_rate
return pf_deduction

def calculate_tds(self):
tds_rate = 0.10 # Assuming 10% of total taxable income for TDS deduction
taxable_income = self.basic_salary + self.hra + self.medical_allowance +
self.other_allowance - self.investments_80c
tds_deduction = taxable_income * tds_rate
return tds_deduction

def calculate_net_salary(self):
pf_deduction = self.calculate_pf()
tds_deduction = self.calculate_tds()
total_deductions = pf_deduction + tds_deduction
net_salary = self.basic_salary + self.hra + self.medical_allowance + self.other_allowance -
total_deductions

20IT425 29
4IT01: Python Programming

return net_salary

if __name__ == "__main__":
name = input("Enter employee name: ")
basic_salary = float(input("Enter basic salary: "))
hra = float(input("Enter HRA: "))
medical_allowance = float(input("Enter medical allowance: "))
other_allowance = float(input("Enter other allowance: "))
investments_80c = float(input("Enter investments under 80C: "))

employee = EmployeeSalarySystem(name, basic_salary, hra, medical_allowance,


other_allowance, investments_80c)

net_salary = employee.calculate_net_salary()
print(f"Net Salary for {employee.name}: {net_salary:.2f}")

Output:

20IT425 30

You might also like