Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
37 views

python_record_code

Uploaded by

kalpanaapj
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)
37 views

python_record_code

Uploaded by

kalpanaapj
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/ 33

1.

PERIMETER AND AREA OF A PARALLELOGRAM

base = int(input("Enter Base value: "))


side = int(input("Enter side value: "))
height = int(input("Enter Height value: "))
if(base>0 and side>0 and height>0):
#Perimeter of parallelogram
print("Perimeter of a parallelogram: ", 2*(base+side))
#Area of parallelogram
print("Area of a parallelogram: ", base*height)
else:
print("Please Enter Positive Number.")

OUTPUT:
2. SIMPLE AND COMPOUND INTEREST

p=int(input("Enter Principle Amnt: "))


n=int(input("Enter No.of.Years: "))
r=int(input("Enter Rate.of.Interest: "))
if(p>0):
#Simple Interest
SI = (p*n*r)/100
print("Simple Interest: ",SI)
#Compound Interest
CI = p * ((1 + r / 100) ** n - 1)
print("Compound Interest: ",CI)
else:
print("Please Enter valid Principle Amount.")

OUTPUT:
3. CONVERSION OF TEMPERATURE

F = float(input("Enter Fahrenheit value: "))


C = float(input("Enter Celsius value: "))
#Fahrenheit to Celsius
celsius_value = (F - 32) * 5 / 9
print(f"Fahrenheit to Celsius: {F}F is {celsius_value:.2f}C")
#Celsius to Fahrenheit
fahrenheit_value = (C * 9 / 5) + 32
print(f"Celsius to Fahrenheit: {C}C is {fahrenheit_value:.2f}F")

OUTPUT:
4. NUMBERS AND ITS FUNCTIONS
a. SUM OF DIGITS

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


sum_num = 0
while(number>0):
digit = number % 10
sum_num += digit
number = number // 10
print("Sum of number is: ",sum_num)

OUTPUT:
b. COUNT THE DIGITS

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


count=0
while(number>0):
count += 1
number = number // 10
print("Number of Digits: ",count)

OUTPUT:
c. PALINDROME

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


num = number
reverse = 0
while(number>0):
remainder = number%10
reverse = reverse*10+remainder
number = number//10
if(reverse == num):
print("It is a palindrome number.")
else:
print("It is not a palindrome number.")

OUTPUT:
5. PERFECT NUMBERS

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


if(n>1):
for number in range(1,n+1):
divisor=0
for i in range(1,number):
if(number % i == 0):
divisor += i
if(number==divisor):
print(number)
else:
print("Enter Valid Number")

OUTPUT:
6. ARMSTRONG NUMBER
n = int(input("Enter a number: "))
count = 0
if(n>1):
for number in range(2,n):
for i in range(2,number):
if(number % i == 0):
break
else:
count +=1
else:
print("Enter Valid Number")
print("Number of Prime Numbers: ",count)

OUTPUT:
7. DISPLAYING LIST ITEMS

list1 = [12,15,32,41,55,74,204,122,132,155,180,200]
print("List: ",list1)
print("Divisible by 4 upto 200: ")
n=len(list1)
for i in range(n):
if(list1[i] <= 200):
if(list1[i]%4 == 0):
print(list1[i])
else:
continue

OUTPUT:
8. ARMSTRONG NUMBER

print("Armstrong number from 100 to 400")


for i in range(100,400):
#Power of Digits
temp = i
sum1 = 0
while temp>0:
n = temp%10
sum1 += n**3
temp = temp//10
#Armstrong or not
if(sum1 == i):
print(i)

OUTPUT:
9. PATTERN

print("Pattern: ")
for i in range(1,4):
for j in range(i):
print('* ',end='')
print('\n')

OUTPUT:
10. LIST OPERATION - I

l1 = [10,0,92,-34,12,-67,2,54,49,7]
print("Displaying List Items:")
print(l1)
print("a] Replace the value at position 0 with its negation")
l1[0] = -(l1[0])
print(" ".join(map(str,l1)))
print("b] Add the value 10 to the end of list")
l1.append(10)
print(" ".join(map(str,l1)))
print("c] Insert the value 22 at position 2 in list")
l1[2] = 22
print(" ".join(map(str,l1)))
print("d] Remove the value at position 1 in list")
del l1[1]
print(" ".join(map(str,l1)))
print("e] Add the values in the list newList to the end of list")
l2 = [1,3,5]
l1.extend(l2)
print(" ".join(map(str,l1)))
print("f] Locate the index of the value 7")
try:
index_7 = l1.index(7)
print(f"The Index of 7 is {index_7}")
except valueError:
print("The Value 7 is not in the list")
print("g] Sort the values in list")
sorted_l1 = sorted(l1)
print(" ".join(map(str,sorted_l1)))

OUTPUT:
11. LIST OPERATION - II
a. STRING GROUPING

from itertools import groupby


from operator import itemgetter
items = input("Enter Birds name with space:")
birds = items.split()
birds.sort()
print(f"After Sorting:,{birds}")
group_item = {key:list(group)for key,group in groupby(birds,key=itemgetter(0))}
print("After Spliting:")
for key,group in group_item.items():
print(f"{key},{group}")

OUTPUT:
b. SPLITTING A LIST

lst = []
n = int(input("Enter size of the list:"))
print("Enter List Items:")
for i in range(0,n):
item = int(input())
lst.append(item)
print(lst)
#Splitting
l1 = int(input("Enter the first part length : "))
l2 = int(input("Enter the second part length : "))
part1 = lst[:l1]
part2 = lst[l1:l1+l2]
part3 = lst[l1+l2:]
print("After Splitting:")
print(part1)
print(part2)
print(part3)
OUTPUT:
c. INSERT DATA AND REMOVE DUPLICATES

lst = []
n = int(input("Enter the size of the list: "))
print("Enter the List Items: ")
for i in range(0,n):
item = int(input())
lst.append(item)
print(lst)
#insert
index = int(input("Enter the position to insert: "))
value = int(input("Enter the value to insert: "))
lst.insert(index,value)
print(f"After Inserting an Element: {lst}")

#Remove
remove_item = int(input("Enter the value to remove:"))
if remove_item in lst:
lst.remove(remove_item)
print(f"After Removing an Element: {lst}")
else:
print("Item not present in the list")

#Remove Duplicates
lst = list(dict.fromkeys(lst))
print(f"After Removing Duplicates: {lst}")
OUTPUT:
d. LIST AGGREGATE FUNCTIONS

lst = []
n = int(input("Enter the size of the list: "))
print("Enter the List Items: ")
for i in range(0,n):
item = float(input())
lst.append(item)
print(lst)
#Round the numbers
round_num = [round(i) for i in lst]
print(f"After Rounding: {round_num}")
#Minimum and Maximum Numbers
mini = min(round_num)
maxi = max(round_num)
print(f"Minimum Number: {mini}")
print(f"Maximum Number: {maxi}")
#Sum of all numbers
total = sum(round_num)
print(f"Sum: {total}")
#Unique value
unique = list(set(round_num))
unique.sort()
print("Unique Numbers: ")
for i in range(len(unique)):
print(unique[i], end=' ')
OUTPUT:
12. EXTRACTING AND SORTING LIST OF TUPLES

tuple_list = [(6, 24, 12), (60, 12, 6, -300), (12, -18, 21)]
K=6
divisible_by_k = [tup for tup in tuple_list if all(x % K == 0 for x in tup)]
print("a. Tuples where all elements are divisible by 6:", divisible_by_k)
all_positive = [tup for tup in tuple_list if all(x > 0 for x in tup)]
print("b. Tuples where all elements are positive:", all_positive)
sorted_by_last_element = sorted(tuple_list, key = lambda x: x[-1])
print("c. Tuples sorted by the last element:", sorted_by_last_element)
sorted_by_digits = sorted(tuple_list, key = lambda x: sum(len(str(abs(e))) for e in x))
print("d. Tuples sorted by total digits:", sorted_by_digits)

OUTPUT:
13. TUPLE OPERATIONS

# Function to get a tuple from the user


def get_tuple():
n = int(input("Enter the number of elements in the tuple: "))
t = ()
print(f"Enter {n} elements: ")
for i in range(n):
elem = input(f"Element {i+1}: ")
t += (elem,) # Adding elements manually to the tuple
return t
# Function to compare two tuples
def compare_tuples(t1, t2):
if len(t1) != len(t2):
return "Tuples are not equal."
for i in range(len(t1)):
if t1[i] != t2[i]:
return "Tuples are not equal."
return "Both tuples are equal."
# Function to swap two tuples
def swap_tuples(t1, t2):
print("Before Swap:")
print(f"Tuple 1: {t1}")
print(f"Tuple 2: {t2}")
# Swapping
temp = t1
t1 = t2
t2 = temp
print("After Swap:")
print(f"Tuple 1: {t1}")
print(f"Tuple 2: {t2}")
# Function to concatenate two tuples
def concatenate_tuples(t1, t2):
result = ()
for i in range(len(t1)):
result += (t1[i],)
for i in range(len(t2)):
result += (t2[i],)
return result
# Function to find the length of a tuple
def length_of_tuple(t):
count = 0
for _ in t:
count += 1
return count
# Function to find maximum and minimum element in a tuple
def find_max_min(t):
max_elem = t[0]
min_elem = t[0]
for i in range(1, length_of_tuple(t)):
if t[i] > max_elem:
max_elem = t[i]
if t[i] < min_elem:
min_elem = t[i]
return max_elem, min_elem
# Function to reverse a tuple
def reverse_tuple(t):
result = ()
for i in range(length_of_tuple(t)-1, -1, -1):
result += (t[i],)
return result
# Main logic
t1 = get_tuple()
t2 = get_tuple()
# a. Compare tuples
print("\nComparing tuples...")
print(compare_tuples(t1, t2))
# b. Swap tuples
print("\nSwapping tuples...")
swap_tuples(t1, t2)
# c. Concatenate tuples
print("\nConcatenating tuples...")
concatenated_tuple = concatenate_tuples(t1, t2)
print(f"Concatenated Tuple: {concatenated_tuple}")
# d. Length of a tuple
print("\nFinding the length of Tuple 1...")
print(f"Length of Tuple 1: {length_of_tuple(t1)}")
# e. Maximum and minimum element of a tuple
print("\nFinding maximum and minimum elements in Tuple 1...")
max_elem, min_elem = find_max_min(t1)
print(f"Maximum Element: {max_elem}")
print(f"Minimum Element: {min_elem}")
# f. Reverse a tuple
print("\nReversing Tuple 1...")
reversed_tuple = reverse_tuple(t1)
print(f"Reversed Tuple: {reversed_tuple}")
OUTPUT:
14. STUDENT DETAILS

def create_record():
sid = input("Enter Student ID: ")
name = input("Enter Name: ")
age = int(input("Enter Age: "))
gpa = float(input("Enter GPA: "))
major = input("Enter Major: ")
return (sid, name, age, gpa, major)
def update_gpa(record, new_gpa):
sid, name, age, _, major = record
return (sid, name, age, new_gpa, major)
def change_major(record, new_major):
sid, name, age, gpa, _ = record
return (sid, name, age, gpa, new_major)
def add_grad_year(record, grad_year):
return record + (grad_year,)
student = create_record()
print("\nInitial Student Record:", student)
new_gpa = float(input("\nEnter new GPA to update: "))
updated_gpa = update_gpa(student, new_gpa)
print("Updated GPA Student Record:", updated_gpa)
new_major = input("\nEnter new Major to update: ")
updated_major = change_major(student, new_major)
print("Updated Major Student Record:", updated_major)
grad_year = int(input("\nEnter Graduation Year to add: "))
updated_record = add_grad_year(student, grad_year)
print("Student Record with Graduation Year:", updated_record)
OUTPUT:
15. SALES DETAILS

sales_data = [
("Product 1", [("Q1", 200), ("Q2", 300), ("Q3", 400)]),
("Product 2", [("Q1", 150), ("Q2", 250), ("Q3", 350)]),
("Product 3", [("Q1", 100), ("Q2", 200), ("Q3", 300)]),
]
total_sales = []
for product in sales_data:
total = sum(s for q, s in product[1])
total_sales.append(total)
print("Total Sales for Each Product:", total_sales)
highest_avg_product = None
highest_avg = 0
for product in sales_data:
avg_sales = sum(s for q, s in product[1]) / len(product[1])
if avg_sales > highest_avg:
highest_avg = avg_sales
highest_avg_product = product[0]
print(f"{highest_avg_product} has the highest average sales per quarter: {highest_avg:.2f}")
sorted_products = sorted(zip(sales_data, total_sales), key=lambda x: x[1], reverse=True)
print("Products sorted by total sales:")
for product, total in sorted_products:
print(f"{product[0]}: {total}")
normalized_sales = []
for product in sales_data:
sales_values = [s for q, s in product[1]]
if sales_values:
min_s, max_s = min(sales_values), max(sales_values)
normalized = [(q, (s - min_s) / (max_s - min_s) if max_s != min_s else 0) for q, s in
product[1]]
else:
normalized = []
normalized_sales.append((product[0], normalized))
print("Normalized Sales Data:")
for product in normalized_sales:
print(f"{product[0]}: {product[1]}")

OUTPUT:
16. DICTIONARY OPERATIONS

dict = {'b':20, 'a':35}


for key in dict:
dict[key]= -dict[key]
print(dict)
dict['c'] = 40
print(dict)
sorted_dict = {key : dict[key] for key in sorted(dict)}
print(sorted_dict)
del dict['b']
print(dict)

OUTPUT:
17. PRODUCT DETAILS
n = int(input("Enter no of products: "))
dict = {}
for i in range (0, n):
key = input("Enter product: ")
value = int(input("Enter it's price: "))
dict[key] = value
print(dict)
i = int(input("Enter the no of products to display the price: "))
for j in range (0,i):
product = input("Enter the product: ")
if(product in dict):
print(dict[product])
else:
print("Product is not in the dictionary")
dollar_amt = float(input("Enter the amount in dollar: "))
for key in dict:
if(dict[key] < dollar_amt):
print(key)

OUTPUT:
18. MULTI-LEVEL DICTIONARY

emp_management = {
"HR": {
"Raj": {"age": 30, "position": "Manager", "salary": 50000},
"Nandhini": {"age": 25, "position": "Recruiter", "salary": 30000}
},
"IT": {
"Mohana": {"age": 28, "position": "Developer", "salary": 60000},
"Rithya": {"age": 27, "position": "Tester", "salary": 75000}
},
}
dept = input("Enter department to add employee: ")
name = input("Enter new employee name: ")
age = int(input("Enter employee age: "))
position = input("Enter employee position: ")
salary = int(input("Enter employee salary: "))
emp_management[dept][name] = {"age": age, "position": position, "salary": salary}
# Update salary
dept = input("Enter department to update salary: ")
name = input("Enter employee name whose salary you want to update: ")
new_salary = int(input("Enter new salary: "))
emp_management[dept][name]['salary'] = new_salary
# Find highest salary
dept = input("Enter department to find highest salary: ")
max_emp = max(emp_management[dept], key=lambda emp:
emp_management[dept][emp]['salary'])
print(f"Highest salary in {dept}: {max_emp}
({emp_management[dept][max_emp]['salary']})")
# Average salary
dept = input("Enter department to calculate average salary: ")
avg_salary = sum(emp['salary'] for emp in emp_management[dept].values()) /
len(emp_management[dept])
print(f"Average salary in {dept}: {avg_salary}")
# Transfer employee
old_dept = input("Enter old department for employee transfer: ")
new_dept = input("Enter new department for employee transfer: ")
emp = input("Enter employee name to transfer: ")
emp_management[new_dept][emp] = emp_management[old_dept].pop(emp)
print(f"{emp} has been transferred from {old_dept} to {new_dept}.")

OUTPUT:

You might also like