Subject- Mathematics (CCF)
QUESTION BANK
Semester- II (for both Major and MDC)
Paper Code: MATH-H-SEC2-2-Th
Paper Name: Python Programming and Introduction to Latex
Question Bank for Python Programming
1. Convert number from decimal to binary system.
dec = int(input("Enter the decimal number: "))
def dTb(n):
if n > 1:
dTb(n//2)
print(n % 2,end = '')
dTb(dec)
print()
2. Convert number from decimal to octal system.
3. Convert from Hexadecimal to binary system.
4. Write a program to read one subject mark and print pass or fail. Use single return values function with
argument.
def check_pass_fail(mark):
if mark >= 50:
return "Pass"
else:
return "Fail"
# Input from the user
mark = float(input("Enter the subject mark: "))
# Call the function and print the result
result = check_pass_fail(mark)
print(f"Result: {result}")
5. Find the median of a given set of numbers.
num = [18, 23, 31, 41, 17]
ln = len(num)
num.sort()
if ln % 2 == 0:
median1 = num[ln//2]
median2 = num[ln//2 - 1]
median = (median1 + median2)/2
else:
median = num[ln//2]
print("Median is: " + str(median))
6. Write a Python function that takes two lists and returns True if they have at least one common
member.
def have_common_member(list1, list2):
# Convert lists to sets for efficient membership checking
set1 = set(list1)
set2 = set(list2)
# Check if there is any intersection between the two sets
if set1.intersection(set2):
return True
else:
return False
# Example usage:
list1 = [1, 2, 3, 4, 5]
list2 = [5, 6, 7, 8, 9]
if have_common_member(list1, list2):
print("Lists have at least one common member")
else:
print("Lists do not have any common member")
7. Write a program for Enhanced Multiplication Table Generator.
n = int(input("Enter any Number: "))
lf = int(input("Enter lower factor: "))
uf = int(input("Enter upper factor: "))
for i in range(lf,uf+1):
value = n * i
print(n," * ",i," = ",value)
8. Write down Unit converter code.
import math
import time
"""Unit Converter"""
#variable setting
cat = raw_input ("Which category would you like to convert? we support length(l) and Weight(w): ")
if cat == ("l"):
unit1 = raw_input ("Which unit would you like to convert from: ")
unit2 = raw_input ("Which unit would you like to convert to: ")
num1 = raw_input ("Enter your value: " )
##Calculations
if unit1 == "cm" and unit2 == "m":
ans = float(num1)/100
elif unit1 == "mm" and unit2 == "cm":
ans = float(num1)/10
elif unit1 == "m" and unit2 == "cm":
ans = float(num1)*100
elif unit1 == "cm" and unit2 == "mm":
ans = float(num1)*10
elif unit1 == "mm" and unit2 == "m":
ans = float(num1)/1000
elif unit1 == "m" and unit2 == "mm":
ans = float(num1)*1000
elif unit1 == "km" and unit2 == "m":
ans = float(num1)*1000
elif unit1 == "m" and unit2 == "km":
ans = float(num1)/1000
elif unit1 == "mm" and unit2 == "km":
ans = float(num1)/1000000
9. Write down Fraction Calculator code.
10. Write down Factor Finder code.
N = int(input("Enter the value of N: "))
for x in range (1,N+1):
if N%x==0:
print(x , end=' ')
11. Write down Graphical Equation Solver code.
12. Write down a code for solving Single-Variable Inequalities.
min_val = None
max_val = None
ineqs = (('<', 9), ('>', 4.5), ('<', 5.6), ('>', 4.8))
for i in ineqs:
if i[0] == '<':
# Smaller than:
if max_val is None:
max_val = i[1]
else:
max_val = min(max_val, i[1])
elif i[0] == '>':
# Greater than
if min_val is None:
min_val = i[1]
else:
min_val = max(min_val, i[1])
print(f'The value is between {min_val} and {max_val}')
13. Prepare an investment report by calculating compound interest.
P1 = input("Principal Amount= ")
P1 = float(P1)
r1 = input("Interest Rate= ")
r1 = float(r1)
n1 = input("Number of Compounding Period per Year= ")
n1 = int(n1)
t1 = input("Total Number of Years= ")
t1 = int(t1)
def invest(P, r, n, t):
for period in range(t):
amount = P*(pow((1+r/n), n*(period+1)))
print('Period:', period+1, amount)
return amount
invest(P1, r1, n1, t1)
14.Write a python program to open and write the content to file and read it.
Opening and Closing a Text File in Python
file1 = open("myfile1.txt","a")
file2 = open("myfile2.txt","w+")
file1.close()
file2.close()
Writing and Reading Text File in Python
file = open("myfile.txt", "w")
L = ["This is Delhi \n", "This is Paris \n", "This is London \n"]
file.write("Hello \n")
file.writelines(L)
file.close()
#Again Reading
file = open("myfile.txt", "r+")
print("Output of Read function is ")
print(file.read())
file.close()
15. Write a python program to check whether a given year is leap year or not and also print all the
months of the given year.
def CheckLeap(Year):
if((Year % 400 == 0) or
(Year % 100 != 0) and
(Year % 4 == 0)):
print("Given Year is a leap Year");
else:
print ("Given Year is not a leap Year")
Year = int(input("Enter the number: "))
CheckLeap(Year)
16. Solve
4x1+3x2-5x3=2
-2x1-4x2+5x3=5
8x1+8x2=-3
import numpy as np
A = np.array([[4, 3, -5],
[-2, -4, 5],
[8, 8, 0]])
y = np.array([2, 5, -3])
x = np.linalg.solve(A, y)
print(x)
17. Write a program to ask the user to enter names of their 3 favorite movies and store them in a list.
movies=[]
mov1=input(“enter first movie:”)
mov2=input(“enter second movie:”)
mov3=input(“enter third movie:”)
movies.append(mov1)
movies.append(mov2)
movies.append(mov3)
print(movies)
18. Write a program to check if a list contains a palindrome of elements.
Hints: use copy() method.
list1=[1,2,1]
copy_list=list1.copy()
copy_list1.reverse()
if(copy_list1==list1)
print(“palindrome”)
else:
print(“NOT palindrome”)
19.Write a program to count the members of students with the “A” grade in the following tuple
Grade=(“C”,”D”,”A”,”A”,”B”,”B”,”A”)
print(grade.count(“A”))
20. Store the above values in a list and sort them from “A” to “D”.
grade=(“C”,”D”,”A”,”A”,”B”,”B”,”A”)
grade.sort()
print(grade)
21. Store following word meaning in a python dictionary
Cat=a small animal, table=a piece of furniture, list of facts and figures
Dictionary={
“cat”=”a small animal”
“table”=[“a piece of furniture”, “list of facts and figures”]
}
22. You are given list of subjects for students. Assume one classroom is required for 1 subject. How many
classroom are needed by all students.
“Python”,”Java”,”C++”,”Python”, “Javascript”, “Java”,”Python”, “Java”, “C++”,”C”
subjects {
“Python”,”Java”,”C++”,”Python”, “Javascript”, “Java”,”Python”, “Java”, “C++”,”C”
}
print(len(subjects))
23. Write a program to enter marks of 3 subjects from the user and store them is a dictionary. Start with
an empty dictionary and add one by one. Use subject name as key and marks as values.
marks={}
x=int(int(input(“enter phy:”))
marks.update({“phy”:x})
x=int(int(input(“enter math:”))
marks.update({“math”:x})
x=int(int(input(“enter chem:”))
marks.update({“chem”:x})
print(marks)
24.Write a program to check if a number entered by the user is odd or even.
num=int(input(“Enter marks:”))
if(num%2==0):
print(“entered number is even”)
else:
print(“entered number is odd”)
25. Write a program to find the greatest of 3 numbers entered by the users.
A=int(input(“Enter first number:”))
B=int(input(“Enter second number:”))
C=int(input(“Enter third number:”))
if(A>B and A>C):
print(“First Number is largest”, A)
elif(B>C)
print (“Second number is largest”,B)
else:
print(“Third number is largest”,C)
26. Write a program to find the largest of four numbers entered by the users.
27.Write a program to check if a number is multiple of 7 or not
x=int(input(“Enter number:”))
if(x%7==0):
print(“multiple of 7”)
else:
print(“NOT a multiple”)
28. Write a program to input 2 numbers and print their sum.
val1=float(input(“Enter first number:”))
val2=float(input(“Enter second number:”))
sum=val1+val2
print(“Sum of entered two number is:”sum)
29. Write a program to input side of a square and print its area.
side=float(input(“enter value of the side:”))
area=side*side
print(“Area of the square is :”,area)
30. Write a program to input 2 floating numbers and print their average.
val1=float(input(“enter first number:”))
val2=float(input(“enter second number:”))
avg=(val1+val2)/2
print(avg)
31. Write a program to input 2 int numbers a and b. print True if a is greater than or equal to b, if not
print False.
a=float(input(“Enter first number:”))
b=float(input(“Enter second number:”))
print(a>=b)
32. Python Program for factorial of a number
# Function to calculate factorial iteratively
def factorial_iterative(n):
factorial = 1
for i in range(1, n + 1):
factorial *= i
return factorial
# Example usage
num = 5
factorial_result = factorial_iterative(num)
print(f"The factorial of {num} is {factorial_result}")
33. Python Program for Program to find area of a circle
import math
def calculate_circle_area(radius):
return math.pi * radius ** 2
# Example usage
radius = float(input("Enter the radius of the circle: "))
area = calculate_circle_area(radius)
print(f"The area of a circle with radius {radius} is {area:.2f}")
34. Write a Python program to find the primes in a given interval.
def check_prime(num):
if num <= 1:
return False
if num == 2:
return True # 2 is a prime number
if num % 2 == 0:
return False # Even numbers greater than 2 are not prime
# Check for factors from 3 to the square root of num
sqrt_num = int(num**0.5) + 1
for i in range(3, sqrt_num, 2):
if num % i == 0:
return False
return True
def print_primes_in_interval(start, end):
if start > end:
print("Invalid interval. Start should be less than or equal to end.")
return
print(f"Prime numbers between {start} and {end}:")
for num in range(start, end + 1):
if check_prime(num):
print(num, end=" ")
# Example usage
start = 10
end = 50
print_primes_in_interval(start, end)
35. Python program to check whether a number is Prime or not
def is_prime(num):
if num <= 1:
return False
if num == 2:
return True # 2 is a prime number
if num % 2 == 0:
return False # Even numbers greater than 2 are not prime
# Check for factors from 3 to the square root of num
sqrt_num = int(num**0.5) + 1
for i in range(3, sqrt_num, 2):
if num % i == 0:
return False
return True
# Example usage
number = 29
if is_prime(number):
print(f"{number} is a prime number")
else:
print(f"{number} is not a prime number")
36. Python Program for n-th Fibonacci number
def fibonacci_iterative(n):
if n <= 0:
return None
elif n == 1:
return 0
elif n == 2:
return 1
# Initialize variables for the first two Fibonacci numbers
a, b = 0, 1
# Calculate the n-th Fibonacci number
for _ in range(2, n):
a, b = b, a + b
return b
# Example usage
n = 10
fibonacci_number = fibonacci_iterative(n)
print(f"The {n}-th Fibonacci number is {fibonacci_number}")
37. Python Program for Sum of squares of first n natural numbers
def sum_of_squares(n):
sum_squares = 0
for i in range(1, n + 1):
sum_squares += i ** 2
return sum_squares
# Example usage
n=5
result = sum_of_squares(n)
print(f"The sum of squares of first {n} natural numbers is {result}")
38. Python Program for cube sum of first n natural numbers
def sum_of_cubes(n):
sum_cubes = 0
for i in range(1, n + 1):
sum_cubes += i ** 3
return sum_cubes
# Example usage
n=5
result = sum_of_cubes(n)
print(f"The sum of cubes of first {n} natural numbers is {result}")
39. Solve the following linear equations using Sympy library
x+y=1
x-y =1
# importing library sympy
from sympy import symbols, Eq, solve
# defining symbols used in equations
# or unknown variables
x, y = symbols('x,y')
# defining equations
eq1 = Eq((x+y), 1)
print("Equation 1:")
print(eq1)
eq2 = Eq((x-y), 1)
print("Equation 2")
print(eq2)
# solving the equation
print("Values of 2 unknown variable are as follows:")
print(solve((eq1, eq2), (x, y)))
40. Solve the following linear equations using Sympy library
x+y+z=1
x-y+2z=1
# importing library sympy
from sympy import symbols, Eq, solve
# defining symbols used in equations
# or unknown variables
x, y, z = symbols('x,y,z')
# defining equations
eq1 = Eq((x+y+z), 1)
print("Equation 1:")
print(eq1)
eq2 = Eq((x-y+2*z), 1)
print("Equation 2")
print(eq2)
eq3 = Eq((2*x-y+2*z), 1)
print("Equation 3")
# solving the equation and printing the
# value of unknown variables
print("Values of 3 unknown variable are as follows:")
print(solve((eq1, eq2, eq3), (x, y, z)))
41. Write a Python code for solving quadratic quation
ax^2+bx+c=0
# import complex math module
import cmath
a = float(input('Enter a: '))
b = float(input('Enter b: '))
c = float(input('Enter c: '))
# calculate the discriminant
d = (b**2) - (4*a*c)
# find two solutions
sol1 = (-b-cmath.sqrt(d))/(2*a)
sol2 = (-b+cmath.sqrt(d))/(2*a)
print('The solution are {0} and {1}'.format(sol1,sol2))
42. Find the sine of different degrees
# Import math Library
import math
# Return the sine value of 30 degrees
print(math.sin(math.radians(30)))
# Return the sine value of 90 degrees
print(math.sin(math.radians(90)))
43. Find the cosine of different numbers
import math
# Return the cosine of different numbers
print (math.cos(0.00))
print (math.cos(-1.23))
print (math.cos(10))
print (math.cos(3.14159265359))
44. Find the value of exp(65) and exp(6.89) using Python code
#Import math Library
import math
#find the exponential of the specified value
print(math.exp(65))
print(math.exp(-6.89))
45. Plot a 2D diagram using Sympy library
Hints:
from sympy import symbols
from sympy.plotting import plot
x = symbols('x')
p1 = plot(x**2, show=False)
p2 = plot(x, -x, show=False)
p1.extend(p2)
p1
p1.show()
46. Write a program to find the sum of first n numbers using while.
n=int(input(“enter number:”))
Sum=0
i=1
While i<=n:
Sum+=i
i+=1
print(“total sum=”,sum)
47.Write a program to find the factorials of first n numbers using for.
n=int(input(“enter number:”))
fact=1
for i in range (1,n+1):
fact*=i
print(:factorial=”,fact)
48. Write a recursive function to print all elements in a list
Hints: Use list and index as parameters.
49. Write a function to convert USD to INR.
def converter (usd_val):
inr_val=usd_val*87
print(usd_val,”USD=”,inr_val,”INR”)
converter(100)
50. Write a recursive function to calculate the sum of first n natural numbers.
def calc_su(n):
if(n==0):
return 0
return calc_su(n-1)+n
sum=calc_su(5)
print(sum)
51. Suppose in Python a = False, b = True, c = True, then evaluate the value of the
following expressions:
(a) a or b
(b) (a and b) or c
(c) a and (b or c)
52. What is a list in Python? How can you check if 3 is an element of the list [1, 7, 5,
3, 4]?
53. Write down the syntax of an if-else statement in Python. Write a Python program
using if-else statements to check whether a number is even or odd.
54. Given a list: primes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29], how do you ob-
tain the first four primes?
55. Define dictionary with example in Python.
1. Use SymPy to compute the expression x3 + xey for x = 1.5, y = 0.75.
55. Write a Python program to find the surface area (4πr2 ) of a sphere, where radius of
sphere is given.
56. Write the output of the following codes in Python:
(a) x = ’Hello’; print(x+x)
(b) print(len(["Math", 2, 4, 6]))
(c) print(4%2 + 52 2 + 5/2)
57. Explain the importance of “break” and “continue” statements with examples in Python.
58. Write a Python program to calculate the sum of three given numbers. If the values
are equal, print “The numbers are all equal”.
59. Write the values of y in the following code:
y = [x for x in range(10) if x % 2 == 0]
print(y)
60. Write a Python function to compute:
30
X 1
S=
u2
n=1 n
+1
where u1 = 1, u2 = 1 and un+1 = un + un−1 , n ≥ 2.
61. (i) Find the value of Python code 2∗∗ 6 − 35//66%7.
1
(ii) Use SymPy to find the roots of the equation x4 − x2 + 1 = 0.
(iii) Use SymPy to simplify the expression (x3 + y 3 )(x3 y + 2y 2 ).
62. Write short notes on the list operations:
(i) sort()
(ii) append()
(iii) ]pop()
63. Write a Python program to check whether a year is a leap year or not.
64. Plot the functions f (x) = x2 and g(x) = x3 on the same graph over the interval [−2, 2]
using a dashed line for f (x) and a dotted line for g(x). Also add labels to the axes and
a title to the graph.
65. Plot the following two functions in one graph using SymPy:
(a) f (x) = x2 in [−2, 2] in color black.
(b) g(x) = x3 − 2 in [−2, 2] in color blue.