0% found this document useful (0 votes)
3 views32 pages

100+python Program Collections

The document contains a series of Python programming exercises aimed at Grade IX students, covering topics such as input/output, arithmetic operations, conditional statements, loops, lists, and dictionaries. Each section provides example code snippets for various tasks including calculating areas, checking conditions, and manipulating data structures. Additionally, it outlines a project for developing a money exchange system, detailing requirements, design, coding, testing, and suggestions for improvements.

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)
3 views32 pages

100+python Program Collections

The document contains a series of Python programming exercises aimed at Grade IX students, covering topics such as input/output, arithmetic operations, conditional statements, loops, lists, and dictionaries. Each section provides example code snippets for various tasks including calculating areas, checking conditions, and manipulating data structures. Additionally, it outlines a project for developing a money exchange system, detailing requirements, design, coding, testing, and suggestions for improvements.

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

Prepared By: Deepak Shrestha - SEE COMPUTER SCIENCE =- GRADE IX - 2082

Input/Output

a) Write a program to ask input as “name” from the user and greet the user as he/she provides their
name.

name = input("Enter your name: ")


print(f"Hello, {name}! Welcome!")

b) Write a program to input 3 sides of triangle and print area

import math
a = float(input("Enter the first side of the triangle: "))
b = float(input("Enter the second side of the triangle: "))
c = float(input("Enter the third side of the triangle: "))
s = (a + b + c) / 2
area = [Link](s * (s - a) * (s - b) * (s - c))
print(f"The area of the triangle is: {area:.2f}")

c) Write a program to input a radius and find the area and circumference of circle

import math
radius = float(input("Enter the radius of the circle: "))
area = [Link] * radius ** 2
circumference = 2 * [Link] * radius
print(f"The area of the circle is: {area:.2f}")
print(f"The circumference of the circle is: {circumference:.2f}")

d) Write a program to input 3 digits as integers and calculate their sum and average.

num1 = int(input("Enter the first digit: "))


num2 = int(input("Enter the second digit: "))
num3 = int(input("Enter the third digit: "))
total = num1 + num2 + num3
average = total / 3
print(f"The sum of the digits is: {total}")
print(f"The average of the digits is: {average:.2f}")

e) Write a program to input a diameter and print area of circle and circumference of circle

import math
diameter = float(input("Enter the diameter of the circle: "))
radius = diameter / 2
area = [Link] * radius ** 2
circumference = [Link] * diameter
print(f"The area of the circle is: {area:.2f}")
print(f"The circumference of the circle is: {circumference:.2f}")

1|Page
Prepared By: Deepak Shrestha - SEE COMPUTER SCIENCE =- GRADE IX - 2082
Constant value and Operators

a) Write a program to input a radius and find the area and circumference of the circle.

import math
radius = float(input("Enter the radius of the circle: "))
area = [Link] * radius ** 2
circumference = 2 * [Link] * radius
print(f"The area of the circle is: {area:.2f}")
print(f"The circumference of the circle is: {circumference:.2f}")

b) Write a program to show the use of arithmetic operators. (Perform add, subtract, multiply, divide,
square and modulus between two numbers)

num1 = float(input("Enter the first number: "))


num2 = float(input("Enter the second number: "))
addition = num1 + num2
subtraction = num1 - num2
multiplication = num1 * num2
division = num1 / num2 if num2 != 0 else "undefined (division by zero)"
square_num1 = num1 ** 2
modulus = num1 % num2
print(f"Addition of {num1} and {num2} is: {addition}")
print(f"Subtraction of {num1} and {num2} is: {subtraction}")
print(f"Multiplication of {num1} and {num2} is: {multiplication}")
print(f"Division of {num1} by {num2} is: {division}")
print(f"The square of {num1} is: {square_num1}")
print(f"The modulus of {num1} and {num2} is: {modulus}")

c) Write a program to show the use of a comparison operator between two variables. (Use the following
operators. ==, <=, >=, !=)

num1 = float(input("Enter the first number: "))


num2 = float(input("Enter the second number: "))
is_equal = num1 == num2
is_less_than_equal = num1 <= num2
is_greater_than_equal = num1 >= num2
is_not_equal = num1 != num2
print(f"Is {num1} equal to {num2}? {is_equal}")
print(f"Is {num1} less than or equal to {num2}? {is_less_than_equal}")
print(f"Is {num1} greater than or equal to {num2}? {is_greater_than_equal}")
print(f"Is {num1} not equal to {num2}? {is_not_equal}")

If…..else Statement

a) Write a program using the if statement to check whether the given number is positive.
num = float(input("Enter a number: "))
if num > 0:
print(f"{num} is a positive number.")
else:
print(f"{num} is not a positive number.")
2|Page
Prepared By: Deepak Shrestha - SEE COMPUTER SCIENCE =- GRADE IX - 2082
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)

age = int(input("Enter your age: "))


if age >= 18:
print("You are eligible to vote.")
else:
print("You are not eligible to vote.")

c) Write a program to check whether the given number is even or odd using an if-else statement.

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


if num % 2 == 0:
print(f"{num} is even.")
else:
print(f"{num} is odd.")

d) Write a program to input two numbers and find the smallest number.

num1 = float(input("Enter the first number: "))


num2 = float(input("Enter the second number: "))
if num1 < num2:
print(f"{num1} is the smallest number.")
else:
print(f"{num2} is 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)

marks = float(input("Enter your marks: "))


if marks >= 40:
print("You passed.")
else:
print("You failed.")

f) Write a program that takes 3 numbers as inputs and displays the smallest number.
num1 = float(input("Enter the first number: "))
num2 = float(input("Enter the second number: "))
num3 = float(input("Enter the third number: "))
if num1 <= num2 and num1 <= num3:
print(f"{num1} is the smallest number.")
elif num2 <= num1 and num2 <= num3:
print(f"{num2} is the smallest number.")
else:
print(f"{num3} is the smallest number.")
3|Page
Prepared By: Deepak Shrestha - SEE COMPUTER SCIENCE =- GRADE IX - 2082

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)

color = input("Enter the traffic light color (green, red, orange): ").lower()
if color == "green":
print("Go!")
elif color == "red":
print("Stop!")
elif color == "orange":
print("Be ready!")
else:
print("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)

practical_marks = float(input("Enter your practical marks: "))


theory_marks = float(input("Enter your theory marks: "))
if (0 <= practical_marks <= 100) and (0 <= theory_marks <= 100):
# Check if the student passed
if practical_marks >= 40 and theory_marks >= 40:
print("You passed!")
else:
print("You failed!")
else:
print("Invalid marks entered. Marks should be between 0 and 100.")

For loop
a) Write a program to print numbers from 1-15.

for num in range(1, 16):


print(num)

b) Write a program to print an input name 20 times.

name = input("Enter your name: ")


for _ in range(20):
print(name)
c) Write a program to print the squares of numbers from 1 to 5 using a for loop.

for num in range(1, 6):


print(f"The square of {num} is {num**2}")

4|Page
Prepared By: Deepak Shrestha - SEE COMPUTER SCIENCE =- GRADE IX - 2082
d) Write a program to print first 20 odd numbers

for num in range(1, 40, 2): # Start at 1, go up to 40 (not inclusive), step by 2


print(num)

e) Write a program that takes an integer as input and prints the multiplication table for that number.

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


for i in range(1, 11):
print(f"{number} x {i} = {number * i}")

While loop
a) Write a program to print numbers from 1-20.

num = 1
while num <= 20:
print(num)
num += 1 # Increment the number

b) Write a program to print first 30 even numbers.

num = 2
count = 0
while count < 30:
print(num)
num += 2
count += 1

c) Write a program to calculate the factorial of a given number.


number = int(input("Enter a number to find its factorial: "))
factorial = 1
while number > 0:
factorial *= number
number -= 1 # Decrease the number
print(f"The factorial is: {factorial}")

d) Write a program to print the sum of the first 20 odd numbers.


num = 1
sum_of_odds = 0
count = 0
while count < 20:
sum_of_odds += num
num += 2 # Go to the next odd number
count += 1 # Increase the count
print(f"The sum of the first 20 odd numbers is: {sum_of_odds}")
5|Page
Prepared By: Deepak Shrestha - SEE COMPUTER SCIENCE =- GRADE IX - 2082
e) Write a program to input multi digits numbers and display the sum of the digits.
number = int(input("Enter a multi-digit number: "))
sum_of_digits = 0
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
print(f"The sum of the digits is: {sum_of_digits}")

Lists
1. Write a Python program to create a list of 5 integers and print the list.

numbers = [10, 20, 30, 40, 50]


print("List of integers:", numbers)

2. Write a Python program to print the second and fourth elements of a list.

numbers = [10, 20, 30, 40, 50]


print("Second element:", numbers[1])
print("Fourth element:", numbers[3])

3. 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)

4. Write a Python program to print the first three elements of a list using slicing.

numbers = [10, 20, 30, 40, 50]


print("First three elements:", numbers[:3])

5. Write a Python program to print the length of a list.

numbers = [10, 20, 30, 40, 50]


print("Length of the list:", len(numbers))

6. Write a Python program to iterate through a list and print each element.

numbers = [10, 20, 30, 40, 50]


for num in numbers:
print(num)

6|Page
Prepared By: Deepak Shrestha - SEE COMPUTER SCIENCE =- GRADE IX - 2082
7. Write a Python program to create a list of squares of numbers from 1 to 10 using list comprehension.

squares = [x**2 for x in range(1, 11)]


print("List of squares from 1 to 10:", squares)

8. Write a Python program to remove the third element from a list and print the updated list.

numbers = [10, 20, 30, 40, 50]


[Link](2)
print("Updated list after removing the third element:", numbers)

Dictionaries
1. Write a Python program to create a dictionary with 3 key-value pairs and print the dictionary.

my_dict = {"name": "Alice", "age": 25, "city": "New York"}


print("Dictionary:", my_dict)

2. 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]}")

3. 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)

4. Write a Python program to remove a key-value pair from a dictionary using the del statement and
print the updated dictionary.

my_dict = {"name": "Alice", "age": 25, "city": "New York"}


del my_dict["age"]
print("Updated Dictionary after deletion:", my_dict)

5. Write a Python program to iterate through a dictionary and print all the keys.

my_dict = {"name": "Alice", "age": 25, "city": "New York"}


print("Keys in the dictionary:")
for key in my_dict:
print(key)

7|Page
Prepared By: Deepak Shrestha - SEE COMPUTER SCIENCE =- GRADE IX - 2082
6. 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.

squares_dict = {x: x**2 for x in range(1, 6)}


print("Dictionary of squares:", squares_dict)

7. Write a Python program to check if a specific key exists in a dictionary.

my_dict = {"name": "Alice", "age": 25, "city": "New York"}


key_to_check = "age"
if key_to_check in my_dict:
print(f"Key '{key_to_check}' exists in the dictionary.")
else:
print(f"Key '{key_to_check}' does not exist in the dictionary.")

8. Write a Python program to merge two dictionaries and print the resulting dictionary.

dict1 = {"name": "Alice", "age": 25}


dict2 = {"city": "New York", "email": "alice@[Link]"}
merged_dict = {**dict1, **dict2}
print("Merged Dictionary:", merged_dict)

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:
1. Research and decide on the features to include, such as currency conversion, displaying exchange rates, and
handling errors.
2. Identify the currencies to support (e.g., USD, EUR, GBP, INR, NPR).
Design the Program:
1. Outline the structure of your program using pseudocode or a flowchart.
2. Include functions for key features like fetching exchange rates, converting currencies, and displaying
results.
Write the code
1. Develop the program in Python, ensuring proper use of functions, loops, and conditionals.
2. Organize the code into logical sections with meaningful variable and function names.
3. Add comments for clarity.
Test the Program:
1. Provide sample inputs and validate the outputs.
2. Ensure the program handles errors as well
Document the Analysis:
1. Describe whether the program executed without errors.
2. Provide examples of inputs and outputs to demonstrate functionality.
3. Assess whether the code is well-organized and easy to follow, noting any areas for improvement.
8|Page
Prepared By: Deepak Shrestha - SEE COMPUTER SCIENCE =- GRADE IX - 2082
Suggest Improvements:
1. Propose additional features, such as live rate updates, historical rate tracking, or a graphical user interface.
2. Offer suggestions on how your peer could enhance the program’s functionality or code readability.

# 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}")

9|Page
Prepared By: Deepak Shrestha - SEE COMPUTER SCIENCE =- GRADE IX - 2082
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.")

PROGRAM COLLECTIONS

1. Sum of two numbers

num1 = int(input("Enter first number: "))


num2 = int(input("Enter second number: "))
sum = num1 + num2
print("Sum of two numbers:", sum)

2. Difference of two numbers

num1 = int(input("Enter first number: "))


num2 = int(input("Enter second number: "))
difference = num1 - num2
print("Difference of two numbers:", difference)

3. Product of two numbers

num1 = int(input("Enter first number: "))


num2 = int(input("Enter second number: "))
product = num1 * num2
print("Product of two numbers:", product)

4. Division of two numbers

num1 = int(input("Enter first number: "))


num2 = int(input("Enter second number: "))
division = num1 / num2 if num2 != 0 else "undefined (division by zero)"
print("Division of two numbers:", division)

5. Modulus of two numbers

num1 = int(input("Enter first number: "))


num2 = int(input("Enter second number: "))
remainder = num1 % num2 if num2 != 0 else "undefined (division by zero)"
print("Remainder of two numbers:", remainder)
10 | P a g e
Prepared By: Deepak Shrestha - SEE COMPUTER SCIENCE =- GRADE IX - 2082
6. Find the average of two numbers

num1 = float(input("Enter first number: "))


num2 = float(input("Enter second number: "))
average = (num1 + num2) / 2
print("Average of two numbers:", average)

7. Sum, product, and average of three numbers

num1 = float(input("Enter the first number: "))


num2 = float(input("Enter the second number: "))
num3 = float(input("Enter the third number: "))
sum = num1 + num2 + num3
product = num1 * num2 * num3
average = sum_of_numbers / 3
print(f"Sum of three numbers: {sum }")
print(f"Product of three numbers: {product }")
print(f"Average of three numbers: {average }")
8. Find the square of a number

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


square = num ** 2
print("Square of the number:", square)

9. Find the cube of a number

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


cube = num ** 3
print("Cube of the number:", cube)

10. Area of a rectangle

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


breadth = float(input("Enter the breadth of the rectangle: "))
area = length * breadth
print("Area of the rectangle:", area)

11. Perimeter of a rectangle

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


breadth = float(input("Enter the breadth of the rectangle: "))
perimeter = 2 * (length + breadth)
print("Perimeter of the rectangle:", perimeter)

11 | P a g e
Prepared By: Deepak Shrestha - SEE COMPUTER SCIENCE =- GRADE IX - 2082
12. Area of a circle
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)

14. Simple Interest Calculation

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


rate = float(input("Enter the rate of interest: "))
time = float(input("Enter the time period in years: "))
simple_interest = (principal * rate * time) / 100
print("Simple Interest:", simple_interest)

15. Calculate the total price after tax

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


tax_rate = float(input("Enter the tax rate: "))
total_price = price + (price * tax_rate / 100)
print("Total price after tax:", total_price)

16. Calculate the volume of a cube

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


volume = side ** 3
print("Volume of the cube:", volume)

17. Calculate the area of a square

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


area = side ** 2
print("Area of the square:", perimeter)

18. Calculate the perimeter of a square

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


perimeter = 4 * side
print("Perimeter of the square:", perimeter)

12 | P a g e
Prepared By: Deepak Shrestha - SEE COMPUTER SCIENCE =- GRADE IX - 2082
19. Calculate the area of a triangle

base = float(input("Enter the base of the triangle: "))


height = float(input("Enter the height of the triangle: "))
area = 0.5 * base * height
print("Area of the triangle:", area)

20. Calculate the surface area of a sphere

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


surface_area = 4 * 3.14159 * (radius ** 2)
print("Surface area of the sphere:", surface_area)

21. Calculate the surface area of a cube

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


surface_area = 6 * (side ** 2)
print("Surface area of the cube:", surface_area)

22. Calculate the volume of a cylinder

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


height = float(input("Enter the height of the cylinder: "))
volume = 3.14159 * radius ** 2 * height
print("Volume of the cylinder:", volume)

23. Calculate the volume of a cone

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


height = float(input("Enter the height of the cone: "))
volume = (1/3) * 3.14159 * (radius ** 2) * height
print("Volume of the cone:", volume)

24. Total cost for multiple items

price_per_item = float(input("Enter the price per item: "))


quantity = int(input("Enter the quantity of items: "))
total_cost = price_per_item * quantity
print("Total cost of item:", total_cost)

25. Calculate the perimeter of a triangle

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


13 | P a g e
Prepared By: Deepak Shrestha - SEE COMPUTER SCIENCE =- GRADE IX - 2082
side2 = float(input("Enter the length of the second side: "))
side3 = float(input("Enter the length of the third side: "))
perimeter = side1 + side2 + side3
print("Perimeter of the triangle:", perimeter)

26. Calculate the area of a parallelogram

base = float(input("Enter the base of the parallelogram: "))


height = float(input("Enter the height of the parallelogram: "))
area = base * height
print("Area of the parallelogram:", area)

27. Convert Celsius to Fahrenheit

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


fahrenheit = (celsius * 9/5) + 32
print("Temperature in Fahrenheit:", fahrenheit)

28. Convert Fahrenheit to Celsius

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


celsius = (fahrenheit - 32) * 5/9
print("Temperature in Celsius:", celsius)

29. Convert hours to minutes

hours = float(input("Enter the number of hours: "))


minutes = hours * 60
print("Minutes:", minutes)

30. Convert minutes to hours

minutes = float(input("Enter the number of minutes: "))


hours = minutes / 60
print("Equivalent hours:", hours)

31. Convert minutes to seconds

minutes = float(input("Enter the number of minutes: "))


seconds = minutes * 60
print("Equivalent seconds:", seconds)

32. Convert seconds to hours

14 | P a g e
Prepared By: Deepak Shrestha - SEE COMPUTER SCIENCE =- GRADE IX - 2082
seconds = float(input("Enter the number of seconds: "))
hours = seconds / 3600
print("Equivalent hours:", hours)

33. Convert days to hours

days = float(input("Enter the number of days: "))


hours = days * 24
print("Hours:", hours)

34. Convert hours to days

hours = float(input("Enter the number of hours: "))


days = hours / 24
print("Equivalent days:", days)

35. Convert kilometers to miles

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


miles = kilometers * 0.621371
print("Distance in miles:", miles)

36. Convert kilometers to meters

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


meters = kilometers * 1000
print("Distance in meters:", meters)

37. Convert meters to centimeters

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


centimeters = meters * 100
print("Distance in centimeters:", centimeters)

38. Convert grams to kilograms

grams = float(input("Enter weight in grams: "))


kilograms = grams / 1000
print("Weight in kilograms:", kilograms)

39. Convert kilograms to pounds

kilograms = float(input("Enter weight in kilograms: "))


pounds = kilograms * 2.20462
print("Weight in pounds:", pounds)
15 | P a g e
Prepared By: Deepak Shrestha - SEE COMPUTER SCIENCE =- GRADE IX - 2082

40. Convert liters to milliliters

liters = float(input("Enter volume in liters: "))


milliliters = liters * 1000
print("Volume in milliliters:", milliliters)
41. Convert milliliters to liters

milliliters = float(input("Enter volume in milliliters: "))


liters = milliliters / 1000
print("Volume in liters:", liters)

42. Convert feet to inches

feet = float(input("Enter height in feet: "))


inches = feet * 12
print("Height in inches:", inches)

43. Convert inches to feet

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


feet = inches / 12
print("Height in feet:", feet)

44. Convert kilograms to grams

kilograms = float(input("Enter weight in kilograms: "))


grams = kilograms * 1000
print("Weight in grams:", grams)

45. Write a Python program to solve a quadratic equation of the form ax^2 + bx + c = 0 using the
quadratic formula.

import math

a = float(input("Enter the coefficient a: "))


b = float(input("Enter the coefficient b: "))
c = float(input("Enter the coefficient c: "))
discriminant = b**2 - 4*a*c
root1 = (-b + [Link](discriminant)) / (2*a)
root2 = (-b - [Link](discriminant)) / (2*a)
print(f"The roots of the quadratic equation are: {root1} and {root2}")

46. Python program to convert USD (U.S. Dollars) to Nepali Currency (NPR)

16 | P a g e
Prepared By: Deepak Shrestha - SEE COMPUTER SCIENCE =- GRADE IX - 2082
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")

1. Check if a number is positive or negative

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


if num > 0:
print("The number is positive.")
17 | P a g e
Prepared By: Deepak Shrestha - SEE COMPUTER SCIENCE =- GRADE IX - 2082
elif num < 0:
print("The number is negative.")
else:
print("The number is zero.")

2. Check if a number is positive, negative, or zero

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


if num > 0:
print(f"{num} is positive.")
elif num < 0:
print(f"{num} is negative.")
else:
print(f"{num} is zero.")

3. Check if a number is positive, negative, or zero using ternary operator

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


print("Positive" if num > 0 else "Negative" if num < 0 else "Zero")

4. Check if a number is even or odd

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


if num % 2 == 0:
print(f"{num} is even.")
else:
print(f"{num} is odd.")

5. Find the largest of two numbers


num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
if num1 > num2:
print(f"The largest number is {num1}")
elif num2 > num1:
print(f"The largest number is {num2}")
else:
print("Both numbers are equal.")

6. Determine the minimum of three numbers

num1 = float(input("Enter the first number: "))


num2 = float(input("Enter the second number: "))
num3 = float(input("Enter the third number: "))
18 | P a g e
Prepared By: Deepak Shrestha - SEE COMPUTER SCIENCE =- GRADE IX - 2082
if num1 <= num2 and num1 <= num3:
print(f"The smallest number is {num1}.")
elif num2 <= num1 and num2 <= num3:
print(f"The smallest number is {num2}.")
else:
print(f"The smallest number is {num3}.")

7. Check if a year is a leap year

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


if (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0):
print(f"{year} is a leap year.")
else:
print(f"{year} is not a leap year.")

8. Grade Calculation

marks = float(input("Enter your marks: "))


if marks >= 90:
grade = 'A'
elif marks >= 80:
grade = 'B'
elif marks >= 70:
grade = 'C'
elif marks >= 60:
grade = 'D'
else:
grade = 'F'
print(f"Your grade is {grade}.")
9. Check if a person is eligible to vote

age = int(input("Enter your age: "))


if age >= 18:
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.")
19 | P a g e
Prepared By: Deepak Shrestha - SEE COMPUTER SCIENCE =- GRADE IX - 2082

11. Check if a number is divisible by both 3 and 9

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


if num % 3 == 0 and num % 9 == 0:
print(f"{num} is divisible by both 3 and 9.")
else:
print(f"{num} is not divisible by both 3 and 9.")

12. Check the type of triangle

a = float(input("Enter the first side: "))


b = float(input("Enter the second side: "))
c = float(input("Enter the third side: "))
if a == b == c:
print("The triangle is equilateral.")
elif a == b or b == c or a == c:
print("The triangle is isosceles.")
else:
print("The triangle is scalene.")

13. Check if a number is a multiple of 3 or 7

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


if num % 3 == 0:
print(f"{num} is a multiple of 3.")
elif num % 7 == 0:
print(f"{num} is a multiple of 7.")
else:
print(f"{num} is not a multiple of 3 or 7.")

14. Check if a person can drive based on age

age = int(input("Enter your age: "))


if age >= 18:
print("You are allowed to drive.")
else:
print("You are not allowed to drive.")
15. Check if a triangle is valid

a = float(input("Enter the first side: "))


b = float(input("Enter the second side: "))
c = float(input("Enter the third side: "))
if a + b > c and a + c > b and b + c > a:
print("The triangle is valid.")
20 | P a g e
Prepared By: Deepak Shrestha - SEE COMPUTER SCIENCE =- GRADE IX - 2082
else:
print("The triangle is not valid.")

16. Check if a triangle is right-angled

a = float(input("Enter the first side: "))


b = float(input("Enter the second side: "))
c = float(input("Enter the third side: "))
if a**2 + b**2 == c**2 or a**2 + c**2 == b**2 or b**2 + c**2 == a**2:
print("The triangle is right-angled.")
else:
print("The triangle is not right-angled.")

17. Check if a person is a child, teenager, or adult

age = int(input("Enter your age: "))


if age < 12:
print("You are a child.")
elif 12 <= age < 18:
print("You are a teenager.")
else:
print("You are an adult.")

18. Check if a given temperature is freezing, normal, or hot

temp = float(input("Enter the temperature in Celsius: "))


if temp <= 0:
print("The weather is freezing.")
elif temp < 25:
print("The weather is normal.")
else:
print("The weather is hot.")

19. Check if a number is a perfect square

import math

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


sqrt = [Link](num)
if sqrt * sqrt == num:
print(f"{num} is a perfect square.")
else:
print(f"{num} is not a perfect square.")

21 | P a g e
Prepared By: Deepak Shrestha - SEE COMPUTER SCIENCE =- GRADE IX - 2082

20. Check if a number is a cube number

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


cube_root = round(num ** (1/3))
if cube_root ** 3 == num:
print(f"{num} is a cube number.")
else:
print(f"{num} is not a cube number.")

1. Print numbers from 1 to 10 using a for loop

for i in range(1, 11):


print(i)

2. Print numbers from 1 to 10 using a while loop

i=1
while i <= 10:
print(i)
i += 1

3. Print the first 10 natural numbers in reverse order

for i in range(10, 0, -1):


print(i)

4. Sum of numbers from 1 to 100

total = 0
for i in range(1, 101):
total += i
print("Sum:", total)

5. Print even numbers between 1 and 20

for i in range(2, 21, 2):


print(i)

6. Find the sum of even numbers between 1 and 50

total = 0
for i in range(2, 51, 2):
total += i
print("Sum of even numbers between 1 and 50:", total)
22 | P a g e
Prepared By: Deepak Shrestha - SEE COMPUTER SCIENCE =- GRADE IX - 2082

7. Calculate the sum of all odd numbers from 1 to 100

total = 0
for i in range(1, 101, 2):
total += i
print("Sum of odd numbers between 1 and 100:", total)

8. Sum of the first n natural numbers

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


total = sum(range(1, n + 1))
print(f"Sum of the first {n} natural numbers is {total}")

9. Find the sum of numbers divisible by 3 and 5 between 1 and 100

total = 0
for i in range(1, 101):
if i % 3 == 0 and i % 5 == 0:
total += i
print("Sum of numbers divisible by 3 and 5 between 1 and 100:", total)

10. Print the first 10 multiples of a given number

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


for i in range(1, 11):
print(f"{num} x {i} = {num * i}")

11. Print the sum of the first 20 even numbers

total = 0
for i in range(2, 41, 2):
total += i
print("Sum of the first 20 even numbers:", total)

12. Print the multiplication table of a number

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


for i in range(1, 11):
print(f"{num} x {i} = {num * i}")

13. Factorial of a number using a for loop


23 | P a g e
Prepared By: Deepak Shrestha - SEE COMPUTER SCIENCE =- GRADE IX - 2082

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


factorial = 1
for i in range(1, num + 1):
factorial *= i
print(f"Factorial of {num} is {factorial}")

14. Factorial of a number using a while loop

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


factorial = 1
i=1
while i <= num:
factorial *= i
i += 1
print(f"Factorial of {num} is {factorial}")

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

16. Print the Fibonacci sequence up to n terms using a while loop

n = int(input("Enter the number of terms: "))


a, b = 0, 1
count = 0
while count < n:
print(a, end=" ")
a, b = b, a + b
count += 1

17. Print the sum of the digits of a number

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


sum = 0
while num > 0:
digit = num % 10
sum += digit #
num = num // 10
print("Sum of the digits:", sum)

24 | P a g e
Prepared By: Deepak Shrestha - SEE COMPUTER SCIENCE =- GRADE IX - 2082
18. Check if a number is prime using a while loop

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


i=2
is_prime = True
while i <= num // 2:
if num % i == 0:
is_prime = False
break
i += 1
if is_prime:
print(f"{num} is a prime number.")
else:
print(f"{num} is not a prime number.")

19. Print all prime numbers up to 50

for num in range(2, 51):


for i in range(2, num):
if num % i == 0:
break
else:
print(num)

20. Find the GCD of two numbers using a while loop

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


b = int(input("Enter the second number: "))
while b:
a, b = b, a % b
print(f"GCD is {a}")

21. Find the LCM of two numbers using a for loop

def gcd(a, b):


while b:
a, b = b, a % b
return a

def lcm(a, b):


return a * b // gcd(a, b)

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


b = int(input("Enter the second number: "))
print(f"LCM is {lcm(a, b)}")
25 | P a g e
Prepared By: Deepak Shrestha - SEE COMPUTER SCIENCE =- GRADE IX - 2082

22. Count the number of digits in a number

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


count = 0
while num > 0:
num //= 10
count += 1
print(f"Number of digits:", count)

23. Calculate the power of a number using a for loop

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


exponent = int(input("Enter the exponent: "))
result = 1
for _ in range(exponent):
result *= base
print(f"{base} to the power of {exponent} is {result}")

24. Reverse a number using a while loop


num = int(input("Enter a number: "))
reversed_num = 0
while num > 0:
digit = num % 10
reversed_num = reversed_num * 10 + digit
num = num // 10
print("Reversed number:", reversed_num)

25. Print the sum of squares of numbers from 1 to 10

total = 0
for i in range(1, 11):
total += i ** 2
print("Sum of squares:", total)

26. Print the cube of numbers from 1 to 5

for i in range(1, 6):


print(f"Cube of {i} is {i ** 3}")

27. Check if a number is a palindrome using a while loop

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


original_num = num
reversed_num = 0
26 | P a g e
Prepared By: Deepak Shrestha - SEE COMPUTER SCIENCE =- GRADE IX - 2082
while num > 0:
digit = num % 10
reversed_num = reversed_num * 10 + digit
num //= 10

if original_num == reversed_num:
print(f"{original_num} is a palindrome.")
else:
print(f"{original_num} is not a palindrome.")

28. Print all Armstrong numbers between 100 and 999

for num in range(100, 1000):


sum_of_cubes = sum(int(digit) ** 3 for digit in str(num))
if sum_of_cubes == num:
print(num)

29. Check if a number is an Armstrong number using a while loop

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


sum_of_cubes = 0
temp = num

while temp > 0:


digit = temp % 10
sum_of_cubes += digit ** 3
temp //= 10

if num == sum_of_cubes:
print(f"{num} is an Armstrong number.")
else:
print(f"{num} is not an Armstrong number.")

30. Print the factorial of a number using recursion

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

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


print(f"Factorial of {num} is {factorial(num)}")

31. Print a pyramid pattern of stars


27 | P a g e
Prepared By: Deepak Shrestha - SEE COMPUTER SCIENCE =- GRADE IX - 2082

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


for i in range(1, rows + 1):
print(' ' * (rows - i) + '*' * (2 * i - 1))

32. Print an inverted pyramid pattern of stars

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


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

33. Find the sum of the digits of an integer using a for loop

num = input("Enter a number: ")


total = 0
for digit in num:
total += int(digit)
print("Sum of digits:", total)

34. Calculate the average of numbers entered by the user

total = 0
count = 0
while True:
num = input("Enter a number (or 'done' to finish): ")
if [Link]() == 'done':
break
total += float(num)
count += 1
print("Average:", total / count)

35. Generate a list of squares of numbers from 1 to n

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


squares = [i ** 2 for i in range(1, n + 1)]
print("List of squares:", squares)

36. Print all multiples of 4 between 1 and 100

for i in range(4, 101, 4):


print(i)

37. Check if a number is a perfect square using a while loop

import math
28 | P a g e
Prepared By: Deepak Shrestha - SEE COMPUTER SCIENCE =- GRADE IX - 2082

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


sqrt = [Link](num)
if sqrt * sqrt == num:
print(f"{num} is a perfect square.")
else:
print(f"{num} is not a perfect square.")

38. Check if a number is a perfect number

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


divisors = [i for i in range(1, num) if num % i == 0]
if sum(divisors) == num:
print(f"{num} is a perfect number.")
else:
print(f"{num} is not a perfect number.")

39. Print the factorial of numbers from 1 to n

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


factorial = 1
for i in range(1, n + 1):
factorial *= i
print(f"Factorial of {i} is {factorial}")

40. Find the largest number in a list using a loop

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


largest = lst[0]
for num in lst:
if num > largest:
largest = num
print("Largest number:", largest)

41. Print all prime factors of a given number

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


i=2
while num > 1:
if num % i == 0:
print(i)
num //= i
else:
i += 1

29 | P a g e
Prepared By: Deepak Shrestha - SEE COMPUTER SCIENCE =- GRADE IX - 2082
42. Find the smallest number in a list using a loop

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


smallest = lst[0]
for num in lst:
if num < smallest:
smallest = num
print("Smallest number:", smallest)

43. Print the first n odd numbers

n = int(input("Enter the number of odd numbers: "))


count = 0
i=1
while count < n:
print(i)
i += 2
count += 1

44. Print the first n even numbers

n = int(input("Enter the number of even numbers: "))


count = 0
i=2
while count < n:
print(i)
i += 2
count += 1

45. Count the number of vowels and consonants in a string

string = input("Enter a string: ").lower()


vowels = 'aeiou'
vowel_count = consonant_count = 0
for char in string:
if [Link]():
if char in vowels:
vowel_count += 1
else:
consonant_count += 1
print("Vowels:", vowel_count)
print("Consonants:", consonant_count)

46. Print the reverse of a string using a loop

30 | P a g e
Prepared By: Deepak Shrestha - SEE COMPUTER SCIENCE =- GRADE IX - 2082
string = input("Enter a string: ")
reversed_string = ""
for char in string:
reversed_string = char + reversed_string
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)

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)

48. 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)

49. 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])

50. 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:
31 | P a g e
Prepared By: Deepak Shrestha - SEE COMPUTER SCIENCE =- GRADE IX - 2082
frequency[item] += 1
else:
frequency[item] = 1
print("Frequency of elements:", frequency)

32 | P a g e

You might also like