0% found this document useful (0 votes)
30 views33 pages

Programs

Uploaded by

tubecreativity
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)
30 views33 pages

Programs

Uploaded by

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

1.

Write a program in python to convert meters to kilometers

Program:

def meters_to_kilometers(meters):
return meters / 1000

meters = float(input("Enter distance in meters: "))


kilometers = meters_to_kilometers(meters)
print(f"{meters} meters is equal to {kilometers} kilometers.")

Output

runfile('C:/Users/user/.spyder-py3/temp.py',
wdir='C:/Users/user/.spyder-py3')
Enter distance in meters: 1024
1024.0 meters is equal to 1.024 kilometers.
2. Write a program in python to convert Fahrenheit to Celsius

Program:

def fahrenheit_to_celsius(fahrenheit):
return (fahrenheit - 32) * 5 / 9

fahrenheit = float(input("Enter temperature in Fahrenheit: "))


celsius = fahrenheit_to_celsius(fahrenheit)
print(f"{fahrenheit}°F is equal to {celsius:.2f}°C.")

Output

runfile('C:/Users/user/project/untitled0.py',
wdir='C:/Users/user/project')
Enter temperature in Fahrenheit: 112
112.0°F is equal to 44.44°C.
3. Write a program in python to convert Celsius to Fahrenheit

Program:

def celsius_to_fahrenheit(celsius):
return (celsius * 9 / 5) + 32

celsius = float(input("Enter temperature in Celsius: "))


fahrenheit = celsius_to_fahrenheit(celsius)
print(f"{celsius}°C is equal to {fahrenheit:.2f}°F.")

Output

runfile('C:/Users/user/project/untitled1.py',
wdir='C:/Users/user/project')
Enter temperature in Celsius: 44.44
44.44°C is equal to 111.99°F.
4. Write a program in python to calculate simple interest
Program:

def calculate_simple_interest(principal, rate, time):


return (principal * rate * time) / 100

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


rate = float(input("Enter rate of interest: "))
time = float(input("Enter time in years: "))
interest = calculate_simple_interest(principal, rate, time)
print(f"Simple Interest is: {interest}")

Output

runfile('C:/Users/user/project/untitled2.py',
wdir='C:/Users/user/project')
Enter principal amount: 2000
Enter rate of interest: 7
Enter time in years: 3
Simple Interest is: 420.0
5. Write a program in python to convert dollar to rupees take
the input of the value

Program:

def dollar_to_rupees(dollars, exchange_rate):


return dollars * exchange_rate

exchange_rate = float(input("Enter the current exchange rate (1


Dollar to Rupees): "))
dollars = float(input("Enter amount in dollars: "))
rupees = dollar_to_rupees(dollars, exchange_rate)
print(f"{dollars} dollars is equal to {rupees} rupees.")

Output

runfile('C:/Users/user/project/untitled3.py',
wdir='C:/Users/user/project')
Enter the current exchange rate (1 Dollar to Rupees): 84.36
Enter amount in dollars: 200
200.0 dollars is equal to 16872.0 rupees.
6. Write a program in python to convert inches to centimeter

Program:

def inches_to_centimeters(inches):
return inches * 2.54

inches = float(input("Enter length in inches: "))


centimeters = inches_to_centimeters(inches)
print(f"{inches} inches is equal to {centimeters} centimeters.")

Output

runfile('C:/Users/user/project/untitled4.py',
wdir='C:/Users/user/project')
Enter length in inches: 15
15.0 inches is equal to 38.1 centimeters.
7. Write a program in python to input three sides of a triangle
and check whether its construction is
possible or not and then display what type of triangle it is.
Program:

def triangle_type(a, b, c):


"""
Determine the type of triangle based on the lengths of its
sides.

Parameters:
a (float): Length of side a
b (float): Length of side b
c (float): Length of side c

Returns:
str: Type of triangle or message indicating triangle cannot
be constructed
"""
if a <= 0 or b <= 0 or c <= 0:
return "Sides must be positive numbers."

# Sort the sides to identify the longest side


sides = sorted([a, b, c])
a, b, c = sides # Now a and b are the shorter sides, c is the
longest
# Check triangle inequality
if a + b <= c:
return "Triangle cannot be constructed"

# Determine the type of triangle based on angles


if a**2 + b**2 == c**2:
return "Right-angled triangle"
elif a**2 + b**2 < c**2:
return "Obtuse-angled triangle"
else:
return "Acute-angled triangle"

# Input from user


try:
a = float(input("Enter side a: "))
b = float(input("Enter side b: "))
c = float(input("Enter side c: "))
result = triangle_type(a, b, c)
print(result)
except ValueError:
print("Please enter valid numerical values for the sides.")
Output
runfile('C:/Users/user/.spyder-py3/untitled8.py',
wdir='C:/Users/user/.spyder-py3')
Enter side a: 90
Enter side b: 30
Enter side c: 60
Triangle cannot be constructed
8. Write a program in python to input a year and check whether
it is leap year century or decade or not a leap year
Program:

def is_leap_year(year):
if year % 4 == 0:
if year % 100 == 0:
return year % 400 == 0
return True
return False
year = int(input("Enter a year: "))
if is_leap_year(year):
print(f"{year} is a leap year.")
else:
print(f"{year} is not a leap year.")

Output
runfile('C:/Users/user/project/untitled6.py',
wdir='C:/Users/user/project')
Enter a year: 2024
2024 is a leap year.
Output
runfile('C:/Users/user/project/untitled7.py',
wdir='C:/Users/user/project')
Enter marks for subject 1: 37
Enter marks for subject 2: 24
Enter marks for subject 3: 28
Enter marks for subject 4: 40
Enter marks for subject 5: 34

Subject Marks
Subject 1 37.0
Subject 2 24.0
Subject 3 28.0
Subject 4 40.0
Subject 5 34.0
Average: 32.60
9. Write a program in python to input the marks of five subjects
and display in the following way :-
subject marks total average Grade
Program:

def calculate_average(marks):
"""Calculate the average of a list of marks."""
if len(marks) == 0:
return 0 # Avoid division by zero
return sum(marks) / len(marks)

def calculate_total(marks):
"""Calculate the total of a list of marks."""
return sum(marks)

def determine_grade(average):
"""Determine the grade based on the average marks."""
if 80 <= average <= 90:
return "A"
elif 70 <= average < 80:
return "B+"
elif 60 <= average < 70:
return "B"
elif 50 <= average < 60:
return "C+"
elif 40 <= average < 50:
return "C"
else:
return "Fail"
def main():
marks = []
num_subjects = 5 # Fixed number of subjects

# Collect marks for each subject


for i in range(num_subjects):
while True:
try:
mark = float(input(f"Enter marks for subject {i + 1} (0-100): "))
if mark < 0 or mark > 100: # Check for valid range
print("Marks must be between 0 and 100. Please enter again.")
continue
marks.append(mark)
break # Exit the loop if input is valid
except ValueError:
print("Invalid input. Please enter a numeric value.")

# Calculate total and average


total = calculate_total(marks)
average = calculate_average(marks)

# Determine the grade


grade = determine_grade(average)

# Output the results


print("\nSubject\t\tMarks")
for i, mark in enumerate(marks):
print(f"Subject {i + 1}\t{mark:.2f}") # Format marks to 2 decimal places
print(f"Total: {total:.2f}")
print(f"Average: {average:.2f}")
print(f"Grade: {grade}")

if __name__ == "__main__":
main()

Output
runfile('C:/Users/user/untitled16.py', wdir='C:/Users/user')
Enter marks for subject 1 (0-100): 99
Enter marks for subject 2 (0-100): 86
Enter marks for subject 3 (0-100): 88
Enter marks for subject 4 (0-100): 94
Enter marks for subject 5 (0-100): 79

Subject Marks
Subject 1 99.00
Subject 2 86.00
Subject 3 88.00
Subject 4 94.00
Subject 5 79.00
Total: 446.00
Average: 89.20
Grade: A
10. Write a program in python to check whether a number is a
perfect square or not
Program:

import math

def is_perfect_square(num):
root = math.isqrt(num)
return root * root == num

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


if is_perfect_square(number):
print(f"{number} is a perfect square.")
else:
print(f"{number} is not a perfect square.")

Output

runfile('C:/Users/user/project/untitled8.py',
wdir='C:/Users/user/project')
Enter a number: 226
226 is not a perfect square.
11.Write a program in Python to enter the starting range and ending
range of a given set of number and display the numbers between the
input numbers
Program:

def display_numbers_in_range(start, end):


print(f"Numbers between {start} and {end}:")
for num in range(start + 1, end):
print(num, end=' ')
print()

# Input
start_range = int(input("Enter the starting range: "))
end_range = int(input("Enter the ending range: "))
display_numbers_in_range(start_range, end_range)

Output

runfile('C:/Users/user/untitled10.py', wdir='C:/Users/user')
Enter the starting range: 2
Enter the ending range: 12
Numbers between 2 and 12:
3 4 5 6 7 8 9 10 11
12.Write a program in python to input any digits number and
print the numbers of digits in that number
Program:

def count_digits(number):
return len(str(abs(number))) # Use abs to handle negative numbers

# Input
num = int(input("Enter a number: "))
print(f"The number of digits in {num} is: {count_digits(num)}")

Output

runfile('C:/Users/user/untitled11.py', wdir='C:/Users/user')
Enter a number: 156987
The number of digits in 156987 is: 6
13.Write a program in python to input an number and perform the sum
of its digits
Program:

def sum_of_digits(number):
return sum(int(digit) for digit in str(abs(number))) # Use abs to handle
negative numbers

# Input
num = int(input("Enter a number: "))
print(f"The sum of the digits in {num} is: {sum_of_digits(num)}")

Output

runfile('C:/Users/user/untitled13.py', wdir='C:/Users/user')
Enter a number: 12345
The sum of the digits in 12345 is: 15
14.Write a program in python to input a number And check whether
it’s a palindrome number or not
Program:

def is_palindrome(number):
str_num = str(abs(number)) # Use abs to handle negative numbers
return str_num == str_num[::-1]

# Input
num = int(input("Enter a number: "))
if is_palindrome(num):
print(f"{num} is a palindrome.")
else:
print(f"{num} is not a palindrome.")

Output

runfile('C:/Users/user/untitled9.py', wdir='C:/Users/user')
Enter a number: 41314
41314 is a palindrome.
15.Write a program in python to input a number and check whether it’s
a prime number or not
Program:

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

# Input
num = int(input("Enter a number: "))
if is_prime(num):
print(f"{num} is a prime number.")
else:
print(f"{num} is not a prime number.")

Output

runfile('C:/Users/user/untitled15.py', wdir='C:/Users/user')
Enter a number: 97
97 is a prime number.
16.Write a program in python to input a number and check whether it’s
a krishnamurti number or not
Program:

def is_krishnamurti(number):
sum_of_factorials = sum(factorial(int(digit)) for digit in str(number))
return sum_of_factorials == number

def factorial(n):
if n == 0 or n == 1:
return 1
return n * factorial(n - 1)

# Input
num = int(input("Enter a number: "))
if is_krishnamurti(num):
print(f"{num} is a Krishnamurti number.")
else:
print(f"{num} is not a Krishnamurti number.")

Output

runfile('C:/Users/user/untitled16.py', wdir='C:/Users/user')
Enter a number: 145
145 a Krishnamurti number.
17.Write a program in python to input a number and print its Fibonacci
series
Program:

def fibonacci_series(n):
a, b = 0, 1
print("Fibonacci series:")
for _ in range(n):
print(a, end=' ')
a, b = b, a + b
print()

# Input
num = int(input("Enter the number of terms in Fibonacci series: "))
fibonacci_series(num)

Output
Enter the number of terms in Fibonacci series: 5
Fibonacci series:
01123
18.Write a program in python to print pattern

i) def pattern1(n):
for i in range(1, n + 1):
print(''.join(str(j) for j in range(1, i + 1)))

# Input
pattern1(4)

Output

1
12
123
1234
ii) def pattern2(n):
for i in range(n, 0, -1):
print(''.join(str(j) for j in range(i, n + 1)))

# Input
pattern2(5)

Output

5
45
345
2345
12345
iii) def asterisk_hash_pattern(n):
for i in range(1, n + 1):
# Create a line with alternating '*' and '#'
line = ''.join('*#'[(j % 2)] for j in range(i))
print(line)

# Input
n = int(input("Enter the number of lines for the pattern: "))
asterisk_hash_pattern(n)

Output

*
*#
*#*
*#*#
iv) def pattern3(n):
for i in range(n, 0, -1):
print(str(i) * i)

# Input
pattern3(5)

Output
55555
4444
333
22
1
v) def pattern5(n):
for i in range(1, n + 1):
print(str(i) * i)
# Input
pattern5(5)

Output

1
23
456
78910
vi) def pattern5(n):
for i in range(1, n + 1):
print(str(i) * i)

# Input
pattern5(5)

Output

1
22
333
4444
vii) def pattern6(n):
for i in range(n, 0, -1):
print(''.join(str(j) for j in range(i, 0, -1)))

# Input
n = int(input("Enter the number of lines for the pattern: "))
pattern6(n)

Output

54321
4321
321
21
1
viii) def number_pattern(n):
for i in range(n):
# Start with the first odd number for the current line
start = 2 * (n - i) - 1
line = ''.join(str(start - 2 * j) for j in range(i + 1))
print(line)

# Input
n = int(input("Enter the number of lines for the pattern: "))
number_pattern(n)

Output

1
31
531
7531
97531
ix) def number_pattern(n):
for i in range(n):
# Create the leading spaces
spaces = ' ' * (n - i - 1)
# Create the numbers in decreasing order
numbers = ''.join(str(num) for num in range(i + 1, 0, -1))
# Print the line with leading spaces
print(spaces + numbers)

# Input
n = int(input("Enter the number of lines for the pattern: "))
number_pattern(n)

Output
5
45
345
2345
12345
x) def asterisk_pattern(n):
# Print the upper part of the pattern
for i in range(1, n + 1):
print('*' * i)

# Print the lower part of the pattern


for i in range(n - 1, 0, -1):
print('*' * i)

# Input
n = 4 # You can change this value to print more or fewer lines
asterisk_pattern(n)

Output

*
**
***
****
***
**
*

You might also like