Python Porgram

Q1. Write a program of Volume of Sphere by entered by User
Ans 1.
r = float(input("Enter radius: "))
vol = (4/3) 3.141 r**3
print("Volume of sphere =", vol)
Q2.Write a program that prints a warning message if the weight of a customer's luggage exceeds the allowed limit of 25.
Ans2.
weight = float(input("Enter luggage weight in kg: "))
if weight > 25:
print("Warning! Luggage exceeds the allowed limit of 25 kg.")
else:
print("Luggage weight is within the allowed limit.")
Q3. Let us say a teacher decided to give grades to her students as follows: a. marks greater than or equal to 80 : Excellent b. marks greater than or equal to 65 but less than 80 : Good c. marks greater than or equal to 50 but less than 65: Pass d. Mark less than 50 : Fail.
Ans3.
marks = int(input("Enter marks: "))
if marks >= 80:
print("Excellent")
elif marks >= 65:
print("Good")
elif marks >= 50:
print("Pass")
else:
print("Fail")
Q4. Write an program in python to print even number in range 0 to 9 ( last number not less not than 10 ). Using while Construct.
Ans 4.
i = 0
while i < 10:
print(i)
i += 2
Q 5. Write a program in Python to print the square number in the list using a for loop construct.
Ans 5.
numbers = [1, 2, 3, 4, 5]
for n in numbers:
print(n * n)
Q 6. Write an Program in Python that will print numbers from 1 to 10 only if the number is odd. When the number is even, it goes to the next iteration . When N become 7 it will finish the current while statement and run the next statement which is print * 'all numbers printed' )
Ans 6.
n = 0
while n < 10:
n += 1
if n % 2 == 0:
continue
print(n)
if n == 7:
break
print("All numbers printed")
Ques 7. Write an program in Python to perform the Simple slicing on the list
['a', 'b', 'c' , 'd' ,'e', 'f' , 'g' ,'h', 'i' , 'j', 'k', 'l', 'm' , 'n'], and extract the character from element at index 3 to element at 7 (i.e uppper index-1). Remember that indexing start with 0.
Ans 7.
letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n']
print(letters[3:7])
Q8. write an program in python to swap two numbers without using Intermediate /Temporary Variable . Prompt the user for Input.
Ans8.
a = int(input("Enter first number: "))
b = int(input("Enter second number: "))
a, b = b, a
print("After swapping:")
print("a =", a)
print("b =", b)
Q9. Write a program in Python that Accepts a Sentence and Calculate the Number of Digits, Uppercase and Lowecase Letters.
Ans 9.
s = input("Enter a sentence: ")
digits = uppercase = lowercase = 0
for ch in s:
if ch.isdigit():
digits += 1
elif ch.isupper():
uppercase += 1
elif ch.islower():
lowercase += 1
print("Digits:", digits)
print("Uppercase letters:", uppercase)
print("Lowercase letters:", lowercase)
Q 10. Write an Program in Python to check if a given year is a Leap Year.
Ans 10.
year = int(input("Enter a year: "))
if year % 400 == 0 or (year % 4 == 0 and year % 100 != 0):
print("Leap Year")
else:
print("Not a Leap Year")
Q 11. Write a program to Find:
a. The Transpose of a Matrix
b. Product of two Matrix
c. Sum of two Matrix
Ans 11.
A = [[1, 2],
[3, 4]]
B = [[5, 6],
[7, 8]]
C = [[0, 0], [0, 0]]
for i in range(2):
for j in range(2):
C[i][j] = A[i][j] + B[i][j]
print(C)
Q 12. Write a program in python to display the Fibonacci Sequences up to nth term where n is provided by the user.
Ans 12.
n = int(input("Enter the number of terms: "))
a, b = 0, 1
for i in range(n):
print(a, end=" ")
a, b = b, a + b
Q 13. Write an Function in Python to Find the Factorial of a Number (n) , where n is provided by the user.
Ans 13.
def factorial(n):
fact = 1
for i in range(1, n + 1):
fact *= i
return fact
n = int(input("Enter a number: "))
print("Factorial =", factorial(n))
Q 14. Write a function in Python to calculate the sum, difference, and product of the two numbers passed as arguments to the function.
Ans 14.
def calculate(a, b):
print("Sum =", a + b)
print("Difference =", a - b)
print("Product =", a * b)
x = int(input("Enter first number: "))
y = int(input("Enter second number: "))
calculate(x, y)
Q 15. Write a function in Python which will accept a number within the range of 1 and 20, and find whether it is a prime Number or not, if it is a prime number, function should return True and if not False.
Ans 15.
def is_prime(n):
if n < 2 or n > 20:
return False
for i in range(2, n):
if n % i == 0:
return False
return True
n = int(input("Enter a number (1-20): "))
print(is_prime(n))
Q 16. Write Lambda function and Normal function in Python to get the average of two numbers.
Ans 16.
1. Normal Function
def average(a, b):
return (a + b) / 2
print(average(10, 20))
2. Lambda Function
average = lambda a, b: (a + b) / 2
print(average(10, 20))
Q 17. Write a Python program to sort a list of Tuples using Lambda.
Ans 17.
tuples = [(1, 5), (3, 2), (2, 8), (4, 1)]
tuples.sort(key=lambda x: x[1])
print(tuples)
Q 18. Write a program in Python to perform Following file Operations.
a. Display File Content
b. Create file and add Contents to it.
c. Read, write and Append using with statement
d. to Copy a file from ' original.txt ' to ' Duplicate.txt '
e. to delete a file.
Ans 18.
a. Display File Content
f = open("original.txt", "r")
print(f.read())
f.close()
b. Create a File and Add Contents
f = open("original.txt", "w")
f.write("Hello, this is my file.")
f.close()
c. Read, Write and Append Using with Statement
Read a file:
with open("original.txt", "r") as f:
print(f.read())
Write to a file:
with open("original.txt", "w") as f:
f.write("Welcome to Python.")
Append to a file:
with open("original.txt", "a") as f:
f.write("\nThis is appended text.")
d. Copy original.txt to Duplicate.txt
with open("original.txt", "r") as f:
data = f.read()
with open("Duplicate.txt", "w") as f:
f.write(data)
e. Delete a File
import os
if os.path.exists("original.txt"):
os.remove("original.txt")
print("File deleted successfully.")
else:
print("File does not exist.")
Remember:
| Mode | Meaning |
|---|---|
"r" |
Read |
"w" |
Write (creates or overwrites a file) |
"a" |
Append (adds content at the end) |
with |
Automatically closes the file |
os.remove() |
Deletes a file |
Q 19. Develop a module named calculator.py in Python, which contain three function -- factorial(n): to find factorial of a number, Fibonacci(n): to find Fibonacci series up to givennumber, n. Perform following Tasks:
a. Import the developed module
b. call the functions available in the module
i. to generate Fibonnaci series upto a number , and
ii. to determine factorial of a number entered by user
Ans 19.
Create a module named calculator.py
# calculator.py
def factorial(n):
fact = 1
for i in range(1, n + 1):
fact *= i
return fact
def Fibonacci(n):
a, b = 0, 1
while a <= n:
print(a, end=" ")
a, b = b, a + b
print()
2. Import the module and call its functions
# main.py
import calculator
n = int(input("Enter a number for Fibonacci series: "))
calculator.Fibonacci(n)
n = int(input("Enter a number for factorial: "))
print("Factorial =", calculator.factorial(n))
Q 20. Create a package in Python name Interest and within this package create two modules simple.py and compund.py. The simple.py module contains function Simple_Interest() and Compound.py module contains function Compound_Interest().
Ans 20.
1. Create the following package structure
Interest/
__init__.py
simple.py
compound.py
main.py
2. simple.py — Simple Interest
def Simple_Interest(p, r, t):
return (p * r * t) / 100
3. compound.py — Compound Interest
def Compound_Interest(p, r, t):
return p * (1 + r / 100) ** t - p
- init.py Create an empty file named init.py inside the Interest folder.
main.py — Import and Call Functions
from Interest.simple import Simple_Interest
from Interest.compound import Compound_Interest
p = float(input("Enter Principal: "))
r = float(input("Enter Rate of Interest: "))
t = float(input("Enter Time in years: "))
print("Simple Interest =", Simple_Interest(p, r, t))
print("Compound Interest =", Compound_Interest(p, r, t))
Q 21. Write Python class to :
a. To convert an Integer to a roman numeral
b. To convert a roman numeral to an integer.
Ans 21.
class Roman:
def int_to_roman(self, num):
values = [
(1000, "M"), (900, "CM"), (500, "D"),
(400, "CD"), (100, "C"), (90, "XC"),
(50, "L"), (40, "XL"), (10, "X"),
(9, "IX"), (5, "V"), (4, "IV"), (1, "I")
]
result = ""
for value, symbol in values:
while num >= value:
result += symbol
num -= value
return result
def roman_to_int(self, s):
values = {
"I": 1, "V": 5, "X": 10, "L": 50,
"C": 100, "D": 500, "M": 1000
}
total = 0
for i in range(len(s)):
if i + 1 < len(s) and values[s[i]] < values[s[i + 1]]:
total -= values[s[i]]
else:
total += values[s[i]]
return total
r = Roman()
n = int(input("Enter an integer: "))
print("Roman numeral:", r.int_to_roman(n))
s = input("Enter a Roman numeral: ").upper()
print("Integer:", r.roman_to_int(s))
Q 22 .Write a python class which has two methods get_String and print_String. get_String accepta string from the user and print_String print the string in upper case.
Ans 22.
class String:
def get_String(self):
self.s = input("Enter a string: ")
def print_String(self):
print(self.s.upper())
obj = String()
obj.get_String()
obj.print_String()
Q 23. Write a Python class named Circle constructed by a radius and two methods which will compute the area and the perimeter of a circle.
Ans 23.
import math
class Circle:
def __init__(self, radius):
self.radius = radius
def area(self):
return math.pi * self.radius ** 2
def perimeter(self):
return 2 * math.pi * self.radius
r = float(input("Enter radius: "))
c = Circle(r)
print("Area =", c.area())
print("Perimeter =", c.perimeter())
Q 24. Write a python code to read a dataset (may be CSV file) and print all feature i.e. columns of the dataset. Determine the descriptive statistics i.e. Maximum, Minimum ,Mean, Median,Count,Variance,Standard,Deviation etc. of the numeric features like age,salary etc., may be present in the dataset.
Ans 24.
Install Libraries
pip install pandas
Example CSV file (data.csv)
Name,Age,Salary
Amit,25,30000
Ravi,30,40000
Neha,28,35000
import pandas as pd
# Read CSV file
df = pd.read_csv("data.csv")
# Display all features (columns)
print("Features (Columns):")
print(df.columns.tolist())
# Descriptive statistics of numeric features
print("\nDescriptive Statistics:")
print(df.describe())
# Display individual statistics
numeric = df.select_dtypes(include="number")
print("\nMaximum:\n", numeric.max())
print("\nMinimum:\n", numeric.min())
print("\nMean:\n", numeric.mean())
print("\nMedian:\n", numeric.median())
print("\nCount:\n", numeric.count())
print("\nVariance:\n", numeric.var())
print("\nStandard Deviation:\n", numeric.std())
Q 25. Write a Python program to read a given CSV file
a. Having tab Delimiter
b. As a Dictionary
c. print the content of the columns.
Ans 25.
Example file (data.csv):
Name Age City
Amit 25 Delhi
Ravi 30 Mumbai
a. Read a CSV file having a Tab Delimiter
import csv
with open("data.csv", "r") as f:
reader = csv.reader(f, delimiter='\t')
for row in reader:
print(row)
b. Read a CSV file as a Dictionary
import csv
with open("data.csv", "r") as f:
reader = csv.DictReader(f, delimiter='\t')
for row in reader:
print(row)
c. Print the Content of the Columns
import csv
with open("data.csv", "r") as f:
reader = csv.DictReader(f, delimiter='\t')
for row in reader:
for column, value in row.items():
print(column, ":", value)
Q 26. Write a Python program to write a Python Dictionary to a CSV File. After Writing the CSV File and Display the Content.
Ans 26.
import csv
data = [
{"Name": "Amit", "Age": 25, "City": "Delhi"},
{"Name": "Ravi", "Age": 30, "City": "Mumbai"}
]
# Write dictionary data to CSV file
with open("data.csv", "w", newline="") as f:
writer = csv.DictWriter(f, fieldnames=["Name", "Age", "City"])
writer.writeheader()
writer.writerows(data)
# Display CSV file content
with open("data.csv", "r") as f:
print(f.read())
Q 27. Write a Python Program to write a Python list of lists to a CSV File. After writing the CSV File read the CSV File and Display the Content.
Ans 27.
import csv
data = [
["Name", "Age", "City"],
["Tarun", 23, "Haldwani"],
["Sushma Bisht", 40, "Dehradun"],
["Neha", 28, "Pune"]
]
# Write list of lists to CSV file
with open("data.csv", "w", newline="") as f:
writer = csv.writer(f)
writer.writerows(data)
# Read and display CSV file content
with open("data.csv", "r") as f:
reader = csv.reader(f)
for row in reader:
print(row)
Q 28.
Ans 28.
Comments
Join the discussionNo comments yet. Be the first to comment.

