0% found this document useful (0 votes)
4 views18 pages

Python Program Notes

The document provides a collection of over 100 Python programming exercises covering various topics such as input/output, constants and operators, conditional statements, loops, lists, and dictionaries. Each section includes multiple tasks with specific requirements, such as calculating areas, checking eligibility, and manipulating data structures. It serves as a comprehensive guide for practicing Python programming skills.

Uploaded by

sanjulnakarmi.us
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)
4 views18 pages

Python Program Notes

The document provides a collection of over 100 Python programming exercises covering various topics such as input/output, constants and operators, conditional statements, loops, lists, and dictionaries. Each section includes multiple tasks with specific requirements, such as calculating areas, checking eligibility, and manipulating data structures. It serves as a comprehensive guide for practicing Python programming skills.

Uploaded by

sanjulnakarmi.us
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

100+ Python Program Collections

INPUT / OUTPUT
a) Write a program to ask input as “name” from the user and greet the user as he/she provides their name.
b) Write a program to input 3 sides of triangle and print area.
c) Write a program to input a radius and find the area of circumference of circle.
d) Write a program to input 3 digits as integers and calculate their sum and average.
e) Write a program to input a diameter and print area of circle and circumference of circle.

CONSTANT VALUE AND OPERATORS


a) Write a program to input a radius and find the area of circumference of the circle.
b) Write a program to show the use of arithmetic operators. (Perform add, subtract, multiply, divide, square and modulus between
two numbers)
c) Write a program to show the use of a comparison operator between two variables. (Use the following operators. ==, <=, >=,
!=)

IF…..ELSE STATEMENT
a) Write a program using the if statement to check whether the given number is positive.
b) Write a program that takes people’s age as input and checks whether they are eligible to vote. (Voting age is 18 and above)
c) Write a program to check whether the given number is even or odd using an if-else statement.
d) Write a program to input two numbers and find the smallest number.
e) Write a program that takes students’ marks as an input and checks whether the student passed or failed. (40 or greater is pass
marks)
f) Write a program that takes 3 numbers as inputs and displays the smallest number.
g) Make a program like a traffic light using an if-elif-else statement. Ask input from the user on providing color. (green=go,
red=stop and orange=be ready, any other color=invalid color)
h) Write a program to input practical and theory marks of Computer and check pass or fail. You can also validate whether a user
has entered valid marks or not. (valid marks should be checked for both theory and practical)

FOR LOOP
a) Write a program to print numbers from 1-15.
b) Write a program to print an input name 20 times.
c) Write a program to print the squares of numbers from 1 to 5 using a for loop.
d) Write a program to print first 20 odd numbers.
e) Write a program that takes an integer as input and prints the multiplication table for that number.

WHILE LOOP
a) Write a program to print numbers from 1-20.
b) Write a program to print first 30 even numbers.
c) Write a program to calculate the factorial of a given number.
d) Write a program to print the sum of the first 20 odd numbers.
e) Write a program to input multi digits numbers and display the sum of the digits.

LISTS
a) Write a Python program to create a list of 5 integers and print the list.
b) Write a Python program to print the second and fourth elements of a list.
c) Write a Python program to append a new element to the end of a list and print the updated list.
d) Write a Python program to print the first three elements of a list using slicing.
e) Write a Python program to print the length of a list.
f) Write a Python program to iterate through a list and print each element.
g) Write a Python program to create a list of squares of numbers from 1 to 10 using list comprehension.
h) Write a Python program to remove the third element from a list and print the updated list.

DICTIONARIES
a) Write a Python program to create a dictionary with 3 key-value pairs and print the dictionary.
b) Write a Python program to print the value associated with a specific key in a dictionary.
c) Write a Python program to add a new key-value pair to a dictionary and print the updated dictionary.
d) Write a Python program to remove a key-value pair from a dictionary using the del statement and print the updated dictionary.
e) Write a Python program to iterate through a dictionary and print all the keys.
f) Write a Python program to create a dictionary where the keys are numbers from 1 to 5 and the values are their squares using
dictionary comprehension.
g) Write a Python program to check if a specific key exists in a dictionary.
h) Write a Python program to merge two dictionaries and print the resulting dictionary.
100+ Python Program Collections
INPUT / OUTPUT CONSTANT VALUE AND OPERATORS
a) Write a program to ask input as “name” from the user and greet the user as he/she a) Write a program to input a radius and find the area and circumference of the
provides their name. circle.
name = input("Enter your name: ") import math
print(f"Hello, {name}! Welcome!") radius = float(input("Enter the radius of the circle: "))
area = [Link] * radius ** 2
b) Write a program to input 3 sides of triangle and print area. circumference = 2 * [Link] * radius
import math print(f"The area of the circle is: {area:.2f}")
a = float(input("Enter the first side of the triangle: ")) print(f"The circumference of the circle is: {circumference:.2f}")
b = float(input("Enter the second side of the triangle: "))
c = float(input("Enter the third side of the triangle: ")) b) Write a program to show the use of arithmetic operators. (Perform add, subtract,
s = (a + b + c) / 2 multiply, divide, square and modulus between two numbers)
area = [Link](s * (s - a) * (s - b) * (s - c)) num1 = float(input("Enter the first number: "))
print(f"The area of the triangle is: {area:.2f}") num2 = float(input("Enter the second number: "))
addition = num1 + num2
c) Write a program to input a radius and find the area and circumference of circle. subtraction = num1 - num2
import math multiplication = num1 * num2
radius = float(input("Enter the radius of the circle: ")) division = num1 / num2 if num2 != 0 else "undefined (division by zero)"
area = [Link] * radius ** 2 square_num1 = num1 ** 2 modulus = num1 % num2
circumference = 2 * [Link] * radius print(f"Addition of {num1} and {num2} is: {addition}")
print(f"The area of the circle is: {area:.2f}") print(f"Subtraction of {num1} and {num2} is: {subtraction}")
print(f"The circumference of the circle is: {circumference:.2f}") print(f"Multiplication of {num1} and {num2} is: {multiplication}")
print(f"Division of {num1} by {num2} is: {division}")
d) Write a program to input 3 digits as integers and calculate their sum and average. print(f"The square of {num1} is: {square_num1}")
num1 = int(input("Enter the first digit: ")) print(f"The modulus of {num1} and {num2} is: {modulus}")
num2 = int(input("Enter the second digit: "))
num3 = int(input("Enter the third digit: ")) c) Write a program to show the use of a comparison operator between two variables.
total = num1 + num2 + num3 (Use the following operators. ==, <=, >=, !=)
average = total / 3 num1 = float(input("Enter the first number: "))
print(f"The sum of the digits is: {total}") num2 = float(input("Enter the second number: "))
print(f"The average of the digits is: {average:.2f}") is_equal = num1 == num2
is_less_than_equal = num1 <= num2
e) Write a program to input a diameter and print area of circle and circumference of is_greater_than_equal = num1 >= num2
circle. is_not_equal = num1 != num2
import math print(f"Is {num1} equal to {num2}? {is_equal}")
diameter = float(input("Enter the diameter of the circle: ")) print(f"Is {num1} less than or equal to {num2}? {is_less_than_equal}")
radius = diameter / 2 print(f"Is {num1} greater than or equal to {num2}? {is_greater_than_equal}")
area = [Link] * radius ** 2 print(f"Is {num1} not equal to {num2}? {is_not_equal}")
circumference = [Link] * diameter
print(f"The area of the circle is: {area:.2f}")
print(f"The circumference of the circle is: {circumference:.2f}")
100+ Python Program Collections
IF…..ELSE STATEMENT f) Write a program that takes 3 numbers as inputs and displays the smallest number.
a) Write a program using the if statement to check whether the given number is num1 = float(input("Enter the first number: "))
positive. num2 = float(input("Enter the second number: "))
num = float(input("Enter a number: ")) num3 = float(input("Enter the third number: "))
if num > 0: if num1 <= num2 and num1 <= num3:
print(f"{num} is a positive number.") print(f"{num1} is the smallest number.")
else: elif num2 <= num1 and num2 <= num3:
print(f"{num} is not a positive number.") print(f"{num2} is the smallest number.")
else:
b) Write a program that takes people’s age as input and checks whether they are print(f"{num3} is the smallest number.")
eligible to vote. (Voting age is 18 and above)
age = int(input("Enter your age: ")) g) Make a program like a traffic light using an if-elif-else statement. Ask input from
if age >= 18: the user on providing color. (green=go, red=stop and orange=be ready, any other
print("You are eligible to vote.") color=invalid color)
else: color = input("Enter the traffic light color (green, red, orange): ").lower()
print("You are not eligible to vote.") if color == "green":
print("Go!")
c) Write a program to check whether the given number is even or odd using an if-else elif color == "red":
statement. print("Stop!")
num = int(input("Enter a number: ")) elif color == "orange":
if num % 2 == 0: print("Be ready!")
print(f"{num} is even.") else:
else: print("Invalid color!")
print(f"{num} is odd.")
h) Write a program to input practical and theory marks of Computer and check pass
d) Write a program to input two numbers and find the smallest number. or fail. You can also validate whether a user has entered valid marks or not. (valid
num1 = float(input("Enter the first number: ")) marks should be checked for both theory and practical)
num2 = float(input("Enter the second number: ")) practical_marks = float(input("Enter your practical marks: "))
if num1 < num2: theory_marks = float(input("Enter your theory marks: "))
print(f"{num1} is the smallest number.") if (0 <= practical_marks <= 100) and (0 <= theory_marks <= 100):
else: # Check if the student passed
print(f"{num2} is the smallest number.") if practical_marks >= 40 and theory_marks >= 40:
print("You passed!")
e) Write a program that takes students’ marks as an input and checks whether the else:
student passed or failed. (40 or greater is pass marks) print("You failed!")
marks = float(input("Enter your marks: ")) else:
if marks >= 40: print("Invalid marks entered. Marks should be between 0 and 100.")
print("You passed.")
else:
print("You failed.")
100+ Python Program Collections
FOR LOOP
a) Write a program to print numbers from 1-15. c) Write a program to calculate the factorial of a given number.
for num in range(1, 16): number = int(input("Enter a number to find its factorial: "))
print(num) factorial = 1
while number > 0:
b) Write a program to print an input name 20 times. factorial *= number
name = input("Enter your name: ") number -= 1 # Decrease the number
for _ in range(20): print(f"The factorial is: {factorial}")
print(name)
d) Write a program to print the sum of the first 20 odd numbers.
c) Write a program to print the squares of numbers from 1 to 5 using a for loop. num = 1
for num in range(1, 6): sum_of_odds = 0
print(f"The square of {num} is {num**2}") count = 0
while count < 20:
d) Write a program to print first 20 odd numbers. sum_of_odds += num
for num in range(1, 40, 2): # Start at 1, go up to 40 (not inclusive), step by 2 num += 2 # Go to the next odd number
print(num) count += 1 # Increase the count
print(f"The sum of the first 20 odd numbers is: {sum_of_odds}")
e) Write a program that takes an integer as input and prints the multiplication table
for that number. e) Write a program to input multi digits numbers and display the sum of the digits.
number = int(input("Enter a number: ")) number = int(input("Enter a multi-digit number: "))
for i in range(1, 11): sum_of_digits = 0
print(f"{number} x {i} = {number * i}") while number > 0:
digit = number % 10 # Get the last digit
sum_of_digits += digit # Add the digit to the sum
number = number // 10 # Remove the last digit
WHILE LOOP print(f"The sum of the digits is: {sum_of_digits}")
a) Write a program to print numbers from 1-20.
num = 1
while num <= 20: LISTS
print(num) a) Write a Python program to create a list of 5 integers and print the list.
num += 1 # Increment the number numbers = [10, 20, 30, 40, 50]
print("List of integers:", numbers)
b) Write a program to print first 30 even numbers.
num = 2 b) Write a Python program to print the second and fourth elements of a list.
count = 0 numbers = [10, 20, 30, 40, 50]
while count < 30: print("Second element:", numbers[1])
print(num) print("Fourth element:", numbers[3])
num += 2
count += 1 c) Write a Python program to append a new element to the end of a list and print the
updated list.
numbers = [10, 20, 30, 40, 50]
[Link](60)
print("Updated list:", numbers)
100+ Python Program Collections
d) Write a Python program to print the first three elements of a list using slicing. d) Write a Python program to remove a key-value pair from a dictionary using the
numbers = [10, 20, 30, 40, 50] del statement and print the updated dictionary.
print("First three elements:", numbers[:3]) my_dict = {"name": "Alice", "age": 25, "city": "New York"}
del my_dict["age"]
e) Write a Python program to print the length of a list. print("Updated Dictionary after deletion:", my_dict)
numbers = [10, 20, 30, 40, 50]
print("Length of the list:", len(numbers)) e) Write a Python program to iterate through a dictionary and print all the keys.
my_dict = {"name": "Alice", "age": 25, "city": "New York"}
f) Write a Python program to iterate through a list and print each element. print("Keys in the dictionary:")
numbers = [10, 20, 30, 40, 50] for key in my_dict:
for num in numbers: print(key)
print(num)
f) Write a Python program to create a dictionary where the keys are numbers from
g) Write a Python program to create a list of squares of numbers from 1 to 10 using 1 to 5 and the values are their squares using dictionary comprehension.
list comprehension. squares_dict = {x: x**2 for x in range(1, 6)}
squares = [x**2 for x in range(1, 11)] print("Dictionary of squares:", squares_dict)
print("List of squares from 1 to 10:", squares)
g) Write a Python program to check if a specific key exists in a dictionary.
h) Write a Python program to remove the third element from a list and print the my_dict = {"name": "Alice", "age": 25, "city": "New York"}
updated list. key_to_check = "age"
numbers = [10, 20, 30, 40, 50] if key_to_check in my_dict:
[Link](2) print(f"Key '{key_to_check}' exists in the dictionary.")
print("Updated list after removing the third element:", numbers) else:
print(f"Key '{key_to_check}' does not exist in the dictionary.")

DICTIONARIES h) Write a Python program to merge two dictionaries and print the resulting
a) Write a Python program to create a dictionary with 3 key-value pairs and print the dictionary.
dictionary. dict1 = {"name": "Alice", "age": 25}
my_dict = {"name": "Alice", "age": 25, "city": "New York"} dict2 = {"city": "New York", "email": "alice@[Link]"}
print("Dictionary:", my_dict) merged_dict = {**dict1, **dict2}
print("Merged Dictionary:", merged_dict)
b) Write a Python program to print the value associated with a specific key in a
dictionary.
my_dict = {"name": "Alice", "age": 25, "city": "New York"}
key = "age"
print(f"The value associated with '{key}' is: {my_dict[key]}")

c) Write a Python program to add a new key-value pair to a dictionary and print the
updated dictionary.
my_dict = {"name": "Alice", "age": 25, "city": "New York"}
my_dict["email"] = "alice@[Link]"
print("Updated Dictionary:", my_dict)
Simple Python Program Collections
1. Sum of two numbers 7. Sum, product, and average of three numbers
num1 = int(input("Enter first number: ")) num1 = float(input("Enter the first number: "))
num2 = int(input("Enter second number: ")) num2 = float(input("Enter the second number: "))
sum = num1 + num2 num3 = float(input("Enter the third number: "))
print("Sum of two numbers:", sum) sum = num1 + num2 + num3
product = num1 * num2 * num3
2. Difference of two numbers average = sum_of_numbers / 3
num1 = int(input("Enter first number: ")) print(f"Sum of three numbers: {sum }")
num2 = int(input("Enter second number: ")) print(f"Product of three numbers: {product }")
difference = num1 - num2 print(f"Average of three numbers: {average }")
print("Difference of two numbers:", difference)
8. Find the square of a number
3. Product of two numbers num = float(input("Enter a number: "))
num1 = int(input("Enter first number: ")) square = num ** 2
num2 = int(input("Enter second number: ")) print("Square of the number:", square)
product = num1 * num2
print("Product of two numbers:", product) 9. Find the cube of a number
num = float(input("Enter a number: "))
4. Division of two numbers cube = num ** 3
num1 = int(input("Enter first number: ")) print("Cube of the number:", cube)
num2 = int(input("Enter second number: "))
division = num1 / num2 if num2 != 0 else "undefined (division by zero)" 10. Area of a rectangle
print("Division of two numbers:", division) length = float(input("Enter the length of the rectangle: "))
breadth = float(input("Enter the breadth of the rectangle: "))
5. Modulus of two numbers area = length * breadth
num1 = int(input("Enter first number: ")) print("Area of the rectangle:", area)
num2 = int(input("Enter second number: "))
remainder = num1 % num2 if num2 != 0 else "undefined (division by zero)" 11. Perimeter of a rectangle
print("Remainder of two numbers:", remainder) length = float(input("Enter the length of the rectangle: "))
breadth = float(input("Enter the breadth of the rectangle: "))
6. Find the average of two numbers perimeter = 2 * (length + breadth)
num1 = float(input("Enter first number: ")) print("Perimeter of the rectangle:", perimeter)
num2 = float(input("Enter second number: "))
average = (num1 + num2) / 2 12. Area of a circle
print("Average of two numbers:", average) import math
radius = float(input("Enter the radius of the circle: "))
area = [Link] * radius ** 2
print("Area of the circle:", area)

13. Circumference of a circle


radius = float(input("Enter the radius of the circle: "))
c = 2 * 3.14159 * radius
print("Circumference of the circle:", c)
Simple Python Program Collections
14. Simple Interest Calculation 22. Calculate the volume of a cylinder
principal = float(input("Enter the principal amount: ")) radius = float(input("Enter the radius of the cylinder: "))
rate = float(input("Enter the rate of interest: ")) height = float(input("Enter the height of the cylinder: "))
time = float(input("Enter the time period in years: ")) volume = 3.14159 * radius ** 2 * height
simple_interest = (principal * rate * time) / 100 print("Volume of the cylinder:", volume)
print("Simple Interest:", simple_interest)
23. Calculate the volume of a cone
15. Calculate the total price after tax radius = float(input("Enter the radius of the cone: "))
price = float(input("Enter the price of the item: ")) height = float(input("Enter the height of the cone: "))
tax_rate = float(input("Enter the tax rate: ")) volume = (1/3) * 3.14159 * (radius ** 2) * height
total_price = price + (price * tax_rate / 100) print("Volume of the cone:", volume)
print("Total price after tax:", total_price)
24. Total cost for multiple items
16. Calculate the volume of a cube price_per_item = float(input("Enter the price per item: "))
side = float(input("Enter the side length of the cube: ")) quantity = int(input("Enter the quantity of items: "))
volume = side ** 3 total_cost = price_per_item * quantity
print("Volume of the cube:", volume) print("Total cost of item:", total_cost)

17. Calculate the area of a square 25. Calculate the perimeter of a triangle
side = float(input("Enter the side length of the square: ")) side1 = float(input("Enter the length of the first side: "))
area = side ** 2 side2 = float(input("Enter the length of the second side: "))
print("Area of the square:", perimeter) side3 = float(input("Enter the length of the third side: "))
perimeter = side1 + side2 + side3
18. Calculate the perimeter of a square print("Perimeter of the triangle:", perimeter)
side = float(input("Enter the side length of the square: "))
perimeter = 4 * side 26. Calculate the area of a parallelogram
print("Perimeter of the square:", perimeter) base = float(input("Enter the base of the parallelogram: "))
height = float(input("Enter the height of the parallelogram: "))
19. Calculate the area of a triangle area = base * height
base = float(input("Enter the base of the triangle: ")) print("Area of the parallelogram:", area)
height = float(input("Enter the height of the triangle: "))
area = 0.5 * base * height 27. Convert Celsius to Fahrenheit
print("Area of the triangle:", area) celsius = float(input("Enter temperature in Celsius: "))
fahrenheit = (celsius * 9/5) + 32
20. Calculate the surface area of a sphere print("Temperature in Fahrenheit:", fahrenheit)
radius = float(input("Enter the radius of the sphere: "))
surface_area = 4 * 3.14159 * (radius ** 2) 28. Convert Fahrenheit to Celsius
print("Surface area of the sphere:", surface_area) fahrenheit = float(input("Enter temperature in Fahrenheit: "))
celsius = (fahrenheit - 32) * 5/9
21. Calculate the surface area of a cube print("Temperature in Celsius:", celsius)
side = float(input("Enter the side length of the cube: "))
surface_area = 6 * (side ** 2) 29. Convert hours to minutes
print("Surface area of the cube:", surface_area) hours = float(input("Enter the number of hours: "))
minutes = hours * 60
print("Minutes:", minutes)
Simple Python Program Collections

30. Convert minutes to hours 39. Convert kilograms to pounds


minutes = float(input("Enter the number of minutes: ")) kilograms = float(input("Enter weight in kilograms: "))
hours = minutes / 60 pounds = kilograms * 2.20462
print("Equivalent hours:", hours) print("Weight in pounds:", pounds)

31. Convert minutes to seconds 40. Convert liters to milliliters


minutes = float(input("Enter the number of minutes: ")) liters = float(input("Enter volume in liters: "))
seconds = minutes * 60 milliliters = liters * 1000
print("Equivalent seconds:", seconds) print("Volume in milliliters:", milliliters)

32. Convert seconds to hours 41. Convert milliliters to liters


seconds = float(input("Enter the number of seconds: ")) milliliters = float(input("Enter volume in milliliters: "))
hours = seconds / 3600 liters = milliliters / 1000
print("Equivalent hours:", hours) print("Volume in liters:", liters)

33. Convert days to hours 42. Convert feet to inches


days = float(input("Enter the number of days: ")) feet = float(input("Enter height in feet: "))
hours = days * 24 inches = feet * 12
print("Hours:", hours) print("Height in inches:", inches)

34. Convert hours to days 43. Convert inches to feet


hours = float(input("Enter the number of hours: ")) inches = float(input("Enter height in inches: "))
days = hours / 24 feet = inches / 12
print("Equivalent days:", days) print("Height in feet:", feet)

35. Convert kilometers to miles 44. Convert kilograms to grams


kilometers = float(input("Enter distance in kilometers: ")) kilograms = float(input("Enter weight in kilograms: "))
miles = kilometers * 0.621371 grams = kilograms * 1000
print("Distance in miles:", miles) print("Weight in grams:", grams)

36. Convert kilometers to meters 45. Write a Python program to solve a quadratic equation of the form ax^2 + bx + c =
kilometers = float(input("Enter distance in kilometers: ")) 0 using the quadratic formula.
meters = kilometers * 1000 import math
print("Distance in meters:", meters) a = float(input("Enter the coefficient a: "))
b = float(input("Enter the coefficient b: "))
37. Convert meters to centimeters c = float(input("Enter the coefficient c: "))
meters = float(input("Enter distance in meters: ")) discriminant = b**2 - 4*a*c
centimeters = meters * 100 root1 = (-b + [Link](discriminant)) / (2*a)
print("Distance in centimeters:", centimeters) root2 = (-b - [Link](discriminant)) / (2*a)
print(f"The roots of the quadratic equation are: {root1} and {root2}")
38. Convert grams to kilograms
grams = float(input("Enter weight in grams: "))
kilograms = grams / 1000
print("Weight in kilograms:", kilograms)
Simple Python Program Collections
46. Python program to convert USD (U.S. Dollars) to Nepali Currency (NPR)
usd = float(input("Enter the amount in USD: "))
conversion_rate = 132.52
npr = usd * conversion_rate
print(f"{usd} USD is equal to {npr} NPR")

47. Python program to convert Nepali Currency (NPR) to Indian Currency (INR)
npr = float(input("Enter the amount in Nepali Currency (NPR): "))
conversion_rate = 0.625
inr = npr * conversion_rate
print(f"{npr} NPR is equal to {inr} INR")

48. Python program that takes an input in seconds and converts it into hours, minutes,
and seconds
total_seconds = int(input("Enter the number of seconds: "))
hours = total_seconds // 3600
minutes = (total_seconds % 3600) // 60
seconds = total_seconds % 60
print(f"{total_seconds} seconds is equal to {hours} hours, {minutes} minutes, and
{seconds} seconds.")

49. Python program that takes an input in days and converts it into years, months, and
days
total_days = int(input("Enter the number of days: "))
years = total_days // 365
remaining_days = total_days % 365
months = remaining_days // 30
days = remaining_days % 30
print(f"{total_days} days is equal to {years} years, {months} months, and {days}
days.")

50. Python program to calculate the volume and total surface area of a hemisphere
import math
radius = float(input("Enter the radius of the hemisphere: "))
volume = (2/3) * [Link] * radius**3
surface_area = 3 * [Link] * radius**2
print(f"Volume of the hemisphere: {volume} cubic units")
print(f"Total surface area of the hemisphere: {surface_area} square units")
Conditional Python Program Collections
1. Check if a number is positive or negative 6. Determine the minimum of three numbers
num = float(input("Enter a number: ")) num1 = float(input("Enter the first number: "))
if num > 0: num2 = float(input("Enter the second number: "))
print("The number is positive.") num3 = float(input("Enter the third number: "))
elif num < 0: if num1 <= num2 and num1 <= num3:
print("The number is negative.") else: print("The number is zero.") print(f"The smallest number is {num1}.")
elif num2 <= num1 and num2 <= num3:
2. Check if a number is positive, negative, or zero print(f"The smallest number is {num2}.")
num = float(input("Enter a number: ")) else:
if num > 0: print(f"The smallest number is {num3}.")
print(f"{num} is positive.")
elif num < 0: 7. Check if a year is a leap year
print(f"{num} is negative.") year = int(input("Enter a year: "))
else: if (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0):
print(f"{num} is zero.") print(f"{year} is a leap year.")
else:
3. Check if a number is positive, negative, or zero using ternary operator print(f"{year} is not a leap year.")
num = float(input("Enter a number: "))
print("Positive" if num > else "Negative" if num < 0 else "Zero") 8. Grade Calculation
marks = float(input("Enter your marks: "))
4. Check if a number is even or odd if marks >= 90:
num = int(input("Enter a number: ")) grade = 'A'
if num % 2 == 0: elif marks >= 80:
print(f"{num} is even.") grade = 'B'
else: elif marks >= 70:
print(f"{num} is odd.") grade = 'C'
elif marks >= 60:
5. Find the largest of two numbers grade = 'D'
num1 = float(input("Enter first number: ")) else:
num2 = float(input("Enter second number: ")) grade = 'F'
if num1 > num2: print(f"Your grade is {grade}.")
print(f"The largest number is {num1}")
elif num2 > num1: 9. Check if a person is eligible to vote
print(f"The largest number is {num2}") age = int(input("Enter your age: "))
else: if age >= 18:
print("Both numbers are equal.") print("You are eligible to vote.")
else:
print("You are not eligible to vote.")

10. Check if a number is divisible by 5 and 11


num = int(input("Enter a number: "))
if num % 5 == 0 and num % 11 == 0:
print(f"{num} is divisible by both 5 and 11.")
else:
print(f"{num} is not divisible by both 5 and 11.")
Conditional Python Program Collections

11. Check if a number is divisible by both 3 and 9 16. Check if a triangle is right-angled
num = int(input("Enter a number: ")) a = float(input("Enter the first side: "))
if num % 3 == 0 and num % 9 == 0: b = float(input("Enter the second side: "))
print(f"{num} is divisible by both 3 and 9.") c = float(input("Enter the third side: "))
else: if a**2 + b**2 == c**2 or a**2 + c**2 == b**2 or b**2 + c**2 == a**2:
print(f"{num} is not divisible by both 3 and 9.") print("The triangle is right-angled.")
else:
12. Check the type of triangle print("The triangle is not right-angled.")
a = float(input("Enter the first side: "))
b = float(input("Enter the second side: ")) 17. Check if a person is a child, teenager, or adult
c = float(input("Enter the third side: ")) age = int(input("Enter your age: "))
if a == b == c: if age < 12:
print("The triangle is equilateral.") print("You are a child.")
elif a == b or b == c or a == c: elif 12 <= age < 18:
print("The triangle is isosceles.") print("You are a teenager.")
else: else:
print("The triangle is scalene.") print("You are an adult.")

13. Check if a number is a multiple of 3 or 7 18. Check if a given temperature is freezing, normal, or hot
num = int(input("Enter a number: ")) temp = float(input("Enter the temperature in Celsius: "))
if num % 3 == 0: if temp <= 0:
print(f"{num} is a multiple of 3.") print("The weather is freezing.")
elif num % 7 == 0: elif temp < 25:
print(f"{num} is a multiple of 7.") print("The weather is normal.")
else: else:
print(f"{num} is not a multiple of 3 or 7.") print("The weather is hot.")

14. Check if a person can drive based on age 19. Check if a number is a perfect square
age = int(input("Enter your age: ")) import math
if age >= 18: num = int(input("Enter a number: "))
print("You are allowed to drive.") sqrt = [Link](num)
else: if sqrt * sqrt == num:
print("You are not allowed to drive.") print(f"{num} is a perfect square.")
else:
15. Check if a triangle is valid print(f"{num} is not a perfect square.")
a = float(input("Enter the first side: "))
b = float(input("Enter the second side: ")) 20. Check if a number is a cube number
c = float(input("Enter the third side: ")) num = int(input("Enter a number: "))
if a + b > c and a + c > b and b + c > a: cube_root = round(num ** (1/3))
print("The triangle is valid.") if cube_root ** 3 == num:
else: print(f"{num} is a cube number.")
print("The triangle is not valid.") else:
print(f"{num} is not a cube number.")
Loop Python Program Collections
1. Print numbers from 1 to 10 using a for loop 9. Find the sum of numbers divisible by 3 and 5 between 1 and 100
for i in range(1, 11): total = 0
print(i) for i in range(1, 101):
if i % 3 == 0 and i % 5 == 0:
2. Print numbers from 1 to 10 using a while loop total += i
i=1 print("Sum of numbers divisible by 3 and 5 between 1 and 100:", total)
while i <= 10:
print(i) 10. Print the first 10 multiples of a given number
i += 1 num = int(input("Enter a number: "))
for i in range(1, 11):
3. Print the first 10 natural numbers in reverse order print(f"{num} x {i} = {num * i}")
for i in range(10, 0, -1):
print(i) 11. Print the sum of the first 20 even numbers
total = 0
4. Sum of numbers from 1 to 100 for i in range(2, 41, 2):
total = 0 total += i
for i in range(1, 101): print("Sum of the first 20 even numbers:", total)
total += i
print("Sum:", total) 12. Print the multiplication table of a number
num = int(input("Enter a number: "))
5. Print even numbers between 1 and 20 for i in range(1, 11):
for i in range(2, 21, 2): print(f"{num} x {i} = {num * i}")
print(i)
13. Factorial of a number using a for loop
6. Find the sum of even numbers between 1 and 50 num = int(input("Enter a number: "))
total = 0 factorial = 1
for i in range(2, 51, 2): for i in range(1, num + 1):
total += i factorial *= i
print("Sum of even numbers between 1 and 50:", total) print(f"Factorial of {num} is {factorial}")

7. Calculate the sum of all odd numbers from 1 to 100 14. Factorial of a number using a while loop
total = 0 num = int(input("Enter a number: "))
for i in range(1, 101, 2): factorial = 1
total += i i=1
print("Sum of odd numbers between 1 and 100:", total) while i <= num:
factorial *= i
8. Sum of the first n natural numbers i += 1
n = int(input("Enter a number: ")) print(f"Factorial of {num} is {factorial}")
total = sum(range(1, n + 1))
print(f"Sum of the first {n} natural numbers is {total}") 15. Print the Fibonacci sequence up to a given number
n = int(input("Enter a number: "))
a, b = 0, 1
while a <= n:
print(a, end=" ")
a, b = b, a + b
Loop Python Program Collections
20. Find the GCD of two numbers using a while loop
16. Print the Fibonacci sequence up to n terms using a while loop a = int(input("Enter the first number: "))
n = int(input("Enter the number of terms: ")) b = int(input("Enter the second number: "))
a, b = 0, 1 while b:
count = 0 a, b = b, a % b
while count < n: print(f"GCD is {a}")
print(a, end=" ")
a, b = b, a + b 21. Find the LCM of two numbers using a for loop
count += 1 def gcd(a, b):
while b:
17. Print the sum of the digits of a number a, b = b, a % b
num = int(input("Enter a number: ")) return a
sum = 0
while num > 0: def lcm(a, b):
digit = num % 10 return a * b // gcd(a, b)
sum += digit #
num = num // 10 a = int(input("Enter the first number: "))
print("Sum of the digits:", sum) b = int(input("Enter the second number: "))
print(f"LCM is {lcm(a, b)}")
18. Check if a number is prime using a while loop
num = int(input("Enter a number: ")) 22. Count the number of digits in a number
i=2 num = int(input("Enter a number: "))
is_prime = True count = 0
while i <= num // 2: while num > 0:
if num % i == 0: num //= 10
is_prime = False count += 1
break print(f"Number of digits:", count)
i += 1
if is_prime: 23. Calculate the power of a number using a for loop
print(f"{num} is a prime number.") base = int(input("Enter the base: "))
else: exponent = int(input("Enter the exponent: "))
print(f"{num} is not a prime number.") result = 1
for _ in range(exponent):
19. Print all prime numbers up to 50 result *= base
for num in range(2, 51): print(f"{base} to the power of {exponent} is {result}")
for i in range(2, num):
if num % i == 0: 24. Reverse a number using a while loop
break num = int(input("Enter a number: "))
else: reversed_num = 0
print(num) while num > 0:
digit = num % 10
reversed_num = reversed_num * 10 + digit
num = num // 10
print("Reversed number:", reversed_num)
Loop Python Program Collections
25. Print the sum of squares of numbers from 1 to 10 30. Print the factorial of a number using recursion
total = 0 def factorial(n):
for i in range(1, 11): if n == 1:
total += i ** 2 return 1
print("Sum of squares:", total) else:
return n * factorial(n - 1)
26. Print the cube of numbers from 1 to 5
for i in range(1, 6): num = int(input("Enter a number: "))
print(f"Cube of {i} is {i ** 3}") print(f"Factorial of {num} is {factorial(num)}")

27. Check if a number is a palindrome using a while loop 31. Print a pyramid pattern of stars
num = int(input("Enter a number: ")) rows = int(input("Enter the number of rows: "))
original_num = num for i in range(1, rows + 1):
reversed_num = 0 print(' ' * (rows - i) + '*' * (2 * i - 1))
while num > 0:
digit = num % 10 32. Print an inverted pyramid pattern of stars
reversed_num = reversed_num * 10 + digit rows = int(input("Enter the number of rows: "))
num //= 10 for i in range(rows, 0, -1):
print(' ' * (rows - i) + '*' * (2 * i - 1))
if original_num == reversed_num:
print(f"{original_num} is a palindrome.") 33. Find the sum of the digits of an integer using a for loop
else: num = input("Enter a number: ")
print(f"{original_num} is not a palindrome.") total = 0
for digit in num:
28. Print all Armstrong numbers between 100 and 999 total += int(digit)
for num in range(100, 1000): print("Sum of digits:", total)
sum_of_cubes = sum(int(digit) ** 3 for digit in str(num))
if sum_of_cubes == num: 34. Calculate the average of numbers entered by the user
print(num) total = 0
count = 0
29. Check if a number is an Armstrong number using a while loop while True:
num = int(input("Enter a number: ")) num = input("Enter a number (or 'done' to finish): ")
sum_of_cubes = 0 if [Link]() == 'done':
temp = num break
total += float(num)
while temp > 0: count += 1
digit = temp % 10 print("Average:", total / count)
sum_of_cubes += digit ** 3
temp //= 10 35. Generate a list of squares of numbers from 1 to n
n = int(input("Enter a number: "))
if num == sum_of_cubes: squares = [i ** 2 for i in range(1, n + 1)]
print(f"{num} is an Armstrong number.") print("List of squares:", squares)
else:
print(f"{num} is not an Armstrong number.")
Loop Python Program Collections
36. Print all multiples of 4 between 1 and 100
for i in range(4, 101, 4): 42. Find the smallest number in a list using a loop
print(i) lst = [int(x) for x in input("Enter numbers separated by spaces: ").split()]
smallest = lst[0]
37. Check if a number is a perfect square using a while loop for num in lst:
import math if num < smallest:
num = int(input("Enter a number: ")) smallest = num
sqrt = [Link](num) print("Smallest number:", smallest)
if sqrt * sqrt == num:
print(f"{num} is a perfect square.") 43. Print the first n odd numbers
else: n = int(input("Enter the number of odd numbers: "))
print(f"{num} is not a perfect square.") count = 0
i=1
38. Check if a number is a perfect number while count < n:
num = int(input("Enter a number: ")) print(i)
divisors = [i for i in range(1, num) if num % i == 0] i += 2
if sum(divisors) == num: count += 1
print(f"{num} is a perfect number.")
else: 44. Print the first n even numbers
print(f"{num} is not a perfect number.") n = int(input("Enter the number of even numbers: "))
count = 0
39. Print the factorial of numbers from 1 to n i=2
n = int(input("Enter a number: ")) while count < n:
factorial = 1 print(i)
for i in range(1, n + 1): i += 2
factorial *= i count += 1
print(f"Factorial of {i} is {factorial}")
45. Count the number of vowels and consonants in a string
40. Find the largest number in a list using a loop string = input("Enter a string: ").lower()
lst = [int(x) for x in input("Enter numbers separated by spaces: ").split()] vowels = 'aeiou'
largest = lst[0] vowel_count = consonant_count = 0
for num in lst: for char in string:
if num > largest: if [Link]():
largest = num if char in vowels:
print("Largest number:", largest) vowel_count += 1
else:
41. Print all prime factors of a given number consonant_count += 1
num = int(input("Enter a number: ")) print("Vowels:", vowel_count)
i=2 print("Consonants:", consonant_count)
while num > 1:
if num % i == 0: 46. Print the reverse of a string using a loop
print(i) string = input("Enter a string: ")
num //=i reversed_string = ""
else: for char in string:
i += 1 reversed_string = char + reversed_string
Loop Python Program Collections
print("Reversed string:", reversed_string)

47. Count the frequency of each character in a string


string = input("Enter a string: ").lower()
frequency = {}
for char in string:
if char in frequency:
frequency[char] += 1
else:
frequency[char] = 1
print("Character frequency:", frequency)

48. Print all the factors of a number


num = int(input("Enter a number: "))
for i in range(1, num + 1):
if num % i == 0:
print(i)

49. Calculate the sum of series 1 + 1/2 + 1/3 + ... + 1/n


n = int(input("Enter a number: "))
total = 0
for i in range(1, n + 1):
total += 1 / i
print("Sum of the series:", total)

50. Print the elements of a list in reverse order using a for loop
lst = [int(x) for x in input("Enter numbers separated by spaces: ").split()]
for i in range(len(lst) - 1, -1, -1):
print(lst[i])

51. Count the frequency of elements in a list using a dictionary


lst = [1, 2, 2, 3, 3, 3, 4, 4, 4, 4]
frequency = {}
for item in lst:
if item in frequency:
frequency[item] += 1
else:
frequency[item] = 1
print("Frequency of elements:", frequency)
PROJECT WORK
Develop a money exchange system in Python and write a report on it. Your project should include functionalities for converting
between various currencies using exchange rates.

Steps to Follow:
Understand the Requirements:
a) Research and decide on the features to include, such as currency conversion, displaying exchange rates, and handling errors.
b) Identify the currencies to support (e.g., USD, EUR, GBP, INR, NPR).

Design the Program:


a) Outline the structure of your program using pseudocode or a flowchart.
b) Include functions for key features like fetching exchange rates, converting currencies, and displaying results.

Write the code:


a) Develop the program in Python, ensuring proper use of functions, loops, and conditionals.
b) Organize the code into logical sections with meaningful variable and function names.
c) Add comments for clarity.

Test the Program:


a) Provide sample inputs and validate the outputs.
b) Ensure the program handles errors as well.

Document the Analysis:


a) Describe whether the program executed without errors.
b) Provide examples of inputs and outputs to demonstrate functionality.
c) Assess whether the code is well-organized and easy to follow, noting any areas for improvement.

Suggest Improvements:
a) Propose additional features, such as live rate updates, historical rate tracking, or a graphical user interface.
b) Offer suggestions on how your peer could enhance the program’s functionality or code readability.
PROJECT WORK
# Currency Exchange System (Simple version without functions)

# Dictionary of exchange rates (static example)


exchange_rates = {
"USD": {"EUR": 0.85, "GBP": 0.75, "INR": 74.5, "NPR": 120.5},
"EUR": {"USD": 1.18, "GBP": 0.88, "INR": 87.5, "NPR": 141.5},
"GBP": {"USD": 1.33, "EUR": 1.14, "INR": 100.5, "NPR": 160.5},
"INR": {"USD": 0.013, "EUR": 0.011, "GBP": 0.0099, "NPR": 1.61},
"NPR": {"USD": 0.0083, "EUR": 0.0071, "GBP": 0.0062, "INR": 0.62} }

# Main Program Loop


while True:
print("\nWelcome to the Money Exchange System")
print("1. Convert Currency")
print("2. Display Exchange Rates")
print("3. Exit")

choice = input("Enter your choice (1/2/3): ")

if choice == '1':
# Currency Conversion
from_currency = input("Enter the source currency (USD, EUR, GBP, INR, NPR): ").upper()
to_currency = input("Enter the target currency (USD, EUR, GBP, INR, NPR): ").upper()

# Check if the currencies are valid


if from_currency in exchange_rates and to_currency in exchange_rates[from_currency]:
amount = float(input(f"Enter the amount in {from_currency}: "))
rate = exchange_rates[from_currency][to_currency]
converted_amount = amount * rate
print(f"{amount} {from_currency} = {converted_amount:.2f} {to_currency}")
else:
print("Error: Invalid currencies or conversion rate not available.")

elif choice == '2':


# Display Exchange Rates
print("Exchange Rates:")
for from_currency in exchange_rates:
for to_currency in exchange_rates[from_currency]:
print(f"1 {from_currency} = {exchange_rates[from_currency][to_currency]} {to_currency}")

elif choice == '3':


# Exit the program
print("Thank you for using the Money Exchange System. Goodbye!")
break

else:
# Invalid option
print("Invalid choice. Please enter a valid option.")

You might also like