0% found this document useful (0 votes)
84 views14 pages

Python Project File PDF

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)
84 views14 pages

Python Project File PDF

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/ 14

1. To find the average and grade for given marks.

def calculate_average(marks):
total_marks = sum(marks)
average = total_marks / len(marks)
return average

def assign_grade(average):
if average >= 90:
return 'A'
elif 80 <= average < 90:
return 'B'
elif 70 <= average < 80:
return 'C'
elif 60 <= average < 70:
return 'D'
else:
return 'F'

# Input marks as a list


marks = []

# Get input for marks


num_subjects = int(input("Enter the number of subjects: "))
for i in range(num_subjects):
mark = float(input(f"Enter marks for subject {i+1}: "))
marks.append(mark)

# Calculate average
average = calculate_average(marks)

# Assign grade
grade = assign_grade(average)

# Display results
print(f"\nAverage marks: {average:.2f}")
print(f"Grade: {grade}")

2. To find sale price of an item with given cost and discount (%).
def calculate_sale_price(cost, discount_percentage):
discount_amount = (discount_percentage / 100) * cost
sale_price = cost - discount_amount
return sale_price
# Input cost and discount percentage
cost = float(input("Enter the cost of the item: "))
discount_percentage = float(input("Enter the discount percentage: "))

# Calculate sale price


sale_price = calculate_sale_price(cost, discount_percentage)

# Display result
print(f"\nSale Price: ${sale_price:.2f}")

3. To calculate perimeter/circumference and area of shapes such as triangle, rectangle, square and

circle.

import math

def calculate_triangle_properties(side1, side2, side3):

perimeter = side1 + side2 + side3

s = perimeter / 2 # semi-perimeter for area calculation

area = math.sqrt(s * (s - side1) * (s - side2) * (s - side3))

return perimeter, area

def calculate_rectangle_properties(length, width):

perimeter = 2 * (length + width)

area = length * width

return perimeter, area

def calculate_square_properties(side):

perimeter = 4 * side

area = side * side

return perimeter, area

def calculate_circle_properties(radius):

circumference = 2 * math.pi * radius


area = math.pi * radius**2

return circumference, area

# Get shape choice from the user

shape = input("Enter the shape (triangle, rectangle, square, circle): ").lower()

# Calculate properties based on the shape

if shape == 'triangle':

side1 = float(input("Enter the length of side 1: "))

side2 = float(input("Enter the length of side 2: "))

side3 = float(input("Enter the length of side 3: "))

perimeter, area = calculate_triangle_properties(side1, side2, side3)

elif shape == 'rectangle':

length = float(input("Enter the length of the rectangle: "))

width = float(input("Enter the width of the rectangle: "))

perimeter, area = calculate_rectangle_properties(length, width)

elif shape == 'square':

side = float(input("Enter the length of the square's side: "))

perimeter, area = calculate_square_properties(side)

elif shape == 'circle':

radius = float(input("Enter the radius of the circle: "))

circumference, area = calculate_circle_properties(radius)

else:

print("Invalid shape entered!")

# Display results

if shape in ('triangle', 'rectangle', 'square', 'circle'):

print(f"\nPerimeter/Circumference: {perimeter:.2f}")

print(f"Area: {area:.2f}")
4. To calculate Simple and Compound interest.

def calculate_simple_interest(principal, rate, time):

simple_interest = (principal * rate * time) / 100

return simple_interest

def calculate_compound_interest(principal, rate, time):

compound_interest = principal * (1 + rate / 100)**time - principal

return compound_interest

# Input principal amount, rate of interest, and time period

principal_amount = float(input("Enter the principal amount: "))

rate_of_interest = float(input("Enter the rate of interest per annum: "))

time_period = float(input("Enter the time period in years: "))

# Calculate Simple Interest

simple_interest = calculate_simple_interest(principal_amount, rate_of_interest, time_period)

# Calculate Compound Interest

compound_interest = calculate_compound_interest(principal_amount, rate_of_interest, time_period)

# Display results

print(f"\nSimple Interest: ${simple_interest:.2f}")

print(f"Compound Interest: ${compound_interest:.2f}")

5. To calculate profit-loss for a given Cost and Sell Price.

def calculate_profit_loss(cost, sell_price):

profit_loss = sell_price - cost

return profit_loss

# Input cost and sell price


cost = float(input("Enter the cost of the item: "))

sell_price = float(input("Enter the sell price of the item: "))

# Calculate profit or loss

profit_loss = calculate_profit_loss(cost, sell_price)

# Display result

if profit_loss > 0:

print(f"\nProfit: ${profit_loss:.2f}")

elif profit_loss < 0:

print(f"\nLoss: ${abs(profit_loss):.2f}")

else:

print("\nNo Profit, No Loss.")

6. To calculate EMI for Amount, Period and Interest.

def calculate_emi(principal, interest_rate, time_period):

# Convert annual interest rate to monthly interest rate

monthly_interest_rate = (interest_rate / 100) / 12

# Calculate EMI using the formula

emi = principal * monthly_interest_rate * (1 + monthly_interest_rate)**time_period / ((1 +


monthly_interest_rate)**time_period - 1)

return emi

# Input loan details

principal_amount = float(input("Enter the loan amount: $"))

annual_interest_rate = float(input("Enter the annual interest rate (%): "))

loan_period_in_years = float(input("Enter the loan period in years: "))


# Convert loan period from years to months

loan_period_in_months = int(loan_period_in_years * 12)

# Calculate EMI

emi = calculate_emi(principal_amount, annual_interest_rate, loan_period_in_months)

# Display result

print(f"\nEMI for the loan: ${emi:.2f} per month")

7. To calculate tax - GST / Income Tax.

def calculate_gst_amount(amount, gst_rate):

gst_amount = (gst_rate / 100) * amount

return gst_amount

def calculate_income_tax(income):

# You can implement a more sophisticated income tax calculation logic here

# This is just a simple placeholder for demonstration

income_tax = 0.1 * income

return income_tax

# Get user's choice

tax_type = input("Enter 'GST' or 'Income Tax' to calculate tax: ").lower()

# Calculate tax based on user's choice

if tax_type == 'gst':

amount = float(input("Enter the amount: "))

gst_rate = float(input("Enter the GST rate (%): "))

tax_amount = calculate_gst_amount(amount, gst_rate)

print(f"\nGST Amount: ${tax_amount:.2f}")

elif tax_type == 'income tax':


income = float(input("Enter the income: "))

tax_amount = calculate_income_tax(income)

print(f"\nIncome Tax Amount: ${tax_amount:.2f}")

else:

print("Invalid tax type. Please enter 'GST' or 'Income Tax'.")

8. To find the largest and smallest numbers in a list.

def find_largest_smallest(numbers):

if not numbers:

return None, None # Return None for both largest and smallest if the list is empty

largest = smallest = numbers[0]

for number in numbers:

if number > largest:

largest = number

elif number < smallest:

smallest = number

return largest, smallest

# Input list of numbers

num_list = list(map(float, input("Enter a list of numbers separated by space: ").split()))

# Find largest and smallest numbers

largest, smallest = find_largest_smallest(num_list)

# Display results

if largest is not None and smallest is not None:

print(f"\nLargest number: {largest}")


print(f"Smallest number: {smallest}")

else:

print("The list is empty.")

9. To find the third largest/smallest number in a list.

def find_third_largest_smallest(numbers):

unique_numbers = list(set(numbers)) # Remove duplicates

unique_numbers.sort()

if len(unique_numbers) < 3:

return "List does not have enough elements."

third_largest = unique_numbers[-3]

third_smallest = unique_numbers[2]

return third_largest, third_smallest

# Input list of numbers

numbers = [int(x) for x in input("Enter a list of numbers separated by spaces: ").split()]

# Find third largest and third smallest

result = find_third_largest_smallest(numbers)

# Display results

print("\nThird Largest Number:", result[0])

print("Third Smallest Number:", result[1])

10. To find the sum of squares of the first 100 natural numbers.

def sum_of_squares(n):

return sum(i**2 for i in range(1, n+1))


# Calculate sum of squares for the first 100 natural numbers

result = sum_of_squares(100)

# Display result

print(f"The sum of squares of the first 100 natural numbers is: {result}")

11. To print the first 'n' multiples of given number.

def print_multiples(number, n):

print(f"The first {n} multiples of {number} are:")

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

multiple = number * i

print(f"{number} x {i} = {multiple}")

# Input the number and the count of multiples

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

n = int(input("Enter the count of multiples (n): "))

# Print the multiples

print_multiples(number, n)

12. To count the number of vowels in user entered string.

def count_vowels(input_string):

vowels = "aeiouAEIOU"

vowel_count = 0

for char in input_string:

if char in vowels:

vowel_count += 1

return vowel_count
# Get user input

user_input = input("Enter a string: ")

# Count vowels

vowel_count = count_vowels(user_input)

# Display result

print(f"\nNumber of vowels in the entered string: {vowel_count}")

13. To print the words starting with a alphabet in a user entered string.

def print_words_starting_with_letter(sentence, letter):

words = sentence.split()

filtered_words = [word for word in words if word.startswith(letter.lower()) or


word.startswith(letter.upper())]

if filtered_words:

print(f"Words starting with '{letter}':")

for word in filtered_words:

print(word)

else:

print(f"No words found starting with '{letter}' in the given sentence.")

# Input sentence and letter

user_sentence = input("Enter a sentence: ")

user_letter = input("Enter the alphabet to filter words: ")

# Call the function to print words starting with the specified alphabet

print_words_starting_with_letter(user_sentence, user_letter)

14. To print number of occurrences of a given alphabet in each string.

def count_occurrences(strings, target_alphabet):


occurrences = []

for string in strings:

count = string.lower().count(target_alphabet.lower())

occurrences.append(count)

return occurrences

# Input list of strings

num_strings = int(input("Enter the number of strings: "))

strings = [input(f"Enter string {i + 1}: ") for i in range(num_strings)]

# Input target alphabet

target_alphabet = input("Enter the alphabet to count: ")

# Count occurrences

result = count_occurrences(strings, target_alphabet)

# Display results

for i, count in enumerate(result):

print(f"Occurrences of '{target_alphabet}' in string {i + 1}: {count}")

15. Create a dictionary to store names of states and their capitals.

# Creating a dictionary to store Indian states and their capitals

indian_states_capitals = {

'Andhra Pradesh': 'Amaravati',

'Arunachal Pradesh': 'Itanagar',

'Assam': 'Dispur',

'Bihar': 'Patna',

'Chhattisgarh': 'Raipur',

'Goa': 'Panaji',

'Gujarat': 'Gandhinagar',
'Haryana': 'Chandigarh',

'Himachal Pradesh': 'Shimla',

'Jharkhand': 'Ranchi',

'Karnataka': 'Bengaluru',

'Kerala': 'Thiruvananthapuram',

'Madhya Pradesh': 'Bhopal',

'Maharashtra': 'Mumbai',

'Manipur': 'Imphal',

'Meghalaya': 'Shillong',

'Mizoram': 'Aizawl',

'Nagaland': 'Kohima',

'Odisha': 'Bhubaneswar',

'Punjab': 'Chandigarh',

'Rajasthan': 'Jaipur',

'Sikkim': 'Gangtok',

'Tamil Nadu': 'Chennai',

'Telangana': 'Hyderabad',

'Tripura': 'Agartala',

'Uttar Pradesh': 'Lucknow',

'Uttarakhand': 'Dehradun',

'West Bengal': 'Kolkata'

# Example: Accessing and printing the capital of a specific state

state_to_check = 'Karnataka'

print(f"The capital of {state_to_check} is {indian_states_capitals[state_to_check]}")

16. Create a dictionary of students to store names and marks obtained in 5 subjects.

def create_student_dictionary():

student_dict = {}
num_students = int(input("Enter the number of students: "))

for i in range(num_students):

student_name = input(f"Enter the name of student {i+1}: ")

marks = []

for j in range(5):

mark = float(input(f"Enter marks for subject {j+1} for {student_name}: "))

marks.append(mark)

student_dict[student_name] = marks

return student_dict

# Create the dictionary of students

students = create_student_dictionary()

# Display the dictionary

print("\nStudent Dictionary:")

for student, marks in students.items():

print(f"{student}: {marks}")

17. To print the highest and lowest values in the dictionary.

def find_highest_lowest(dictionary):

if not dictionary:

print("Dictionary is empty.")

return

# Find the key corresponding to the highest value

max_key = max(dictionary, key=dictionary.get)


max_value = dictionary[max_key]

# Find the key corresponding to the lowest value

min_key = min(dictionary, key=dictionary.get)

min_value = dictionary[min_key]

# Print the results

print(f"Highest value: {max_value} (Key: {max_key})")

print(f"Lowest value: {min_value} (Key: {min_key})")

my_dictionary = {'a': 10, 'b': 5, 'c': 20, 'd': 8, 'e': 15}

find_highest_lowest(my_dictionary)

You might also like