Q.
1 Write a program to display the Fibonacci sequences Upto nth term
where n Is provided by the user.
def fibonacci_sequence(n):
"""Prints the Fibonacci sequence up to the nth term."""
if n <= 0:
print("Please enter a positive integer.")
return
elif n == 1:
print("Fibonacci sequence up to 1 term:", 0)
return
# Start with the first two terms
a, b = 0, 1
sequence = [a, b]
# Generate subsequent terms
while len(sequence) < n:
c=a+b
[Link](c)
a=b
b=c
print(f"Fibonacci sequence up to {n} terms:", ", ".join(map(str, sequence)))
# Get user input
try:
n_terms = int(input("Enter the number of terms (n): "))
fibonacci_sequence(n_terms)
except ValueError:
print("Invalid input. Please enter an integer.")
output:
Enter the number of terms (n): 10
Fibonacci sequence up to 10 terms: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34
Process finished with exit code 0
Q. 2Write a program to find the sum of all Odd and Even numbers Upto a
Number specified by the user
def sum_odd_even(limit):
sum_odd = 0
sum_even = 0
for i in range(1, limit + 1):
if i % 2 == 0:
sum_even += i
else:
sum_odd += i
return sum_odd, sum_even
upper_limit = int(input("Enter the upper limit: "))
if upper_limit<= 0:
print("Please enter a positive integer.")
else:
odd_sum, even_sum = sum_odd_even(upper_limit)
print(f"Sum of odd numbers up to {upper_limit}: {odd_sum}")
print(f"Sum of even numbers up to {upper_limit}: {even_sum}")
Output :
Enter the upper limit: 5
Sum of odd numbers up to 5: 9
Sum of even numbers up to 5: 6
Q. 3Write a program to check whether a number is prime or not. Prompt the
User for input
def is_prime(number):
if number <= 1:
return False
for i in range(2, int(number**0.5) + 1):
if number % i == 0:
return False
return True
num = int(input("Enter a number to check if it's prime: "))
if is_prime(num):
print(f"{num} is a prime number.")
else:
print(f"{num} is not a prime number.")
Output :
Enter a number to check if it's prime: 8
8 is not a prime number.
Enter a number to check if it's prime: 5
5 is a prime number.
Q. 4Write Python code to solve the quadratic equation ax**2+bx+c=0 by
Getting input for coefficients from the user
import cmath
def solve_quadratic(a, b, c):
delta = (b**2) - (4*a*c)
sol1 = (-b - [Link](delta)) / (2*a)
sol2 = (-b + [Link](delta)) / (2*a)
return sol1, sol2
a = float(input("Enter coefficient a: "))
b = float(input("Enter coefficient b: "))
c = float(input("Enter coefficient c: "))
if a == 0:
print("Coefficient 'a' cannot be zero for a quadratic equation.")
else:
root1, root2 = solve_quadratic(a, b, c)
print(f"The solutions are {root1} and {root2}")
Output:
Enter coefficient a: 5
Enter coefficient b: 4
Enter coefficient c: 9
The solutions are (-0.4-1.2806248474865698j) and (-
0.4+1.2806248474865698j)
Q. 5 Find the area and perimeter of a circle using functions Prompt the user
for Input.
import math
def circle_area(radius):
return [Link] * radius ** 2
def circle_perimeter(radius):
return 2 * [Link] * radius
r = float(input("Enter the radius of the circle: "))
if r < 0:
print("Radius cannot be negative.")
else:
area = circle_area(r)
perimeter = circle_perimeter(r)
print("Area of the circle:", area)
print("Perimeter of the circle:", perimeter)
Output:
Enter the radius of the circle: 7
Area of the circle: 153.93804002589985
Perimeter of the circle: 43.982297150257104
Q. 6Write a Python program using functions to find the value of nPr and nCr
Without using inbuilt factorial() function
def factorial(n):
if n == 0 or n == 1:
return 1
else:
result = 1
for i in range(2, n + 1):
result *= i
return result
def calculate_nPr(n, r):
if r > n:
return "Invalid input: r cannot be greater than n"
return factorial(n) / factorial(n - r)
def calculate_nCr(n, r):
if r > n:
return "Invalid input: r cannot be greater than n"
return factorial(n) / (factorial(r) * factorial(n - r))
n = int(input("Enter the value of n: "))
r = int(input("Enter the value of r: "))
if r > n or n < 0 or r < 0:
print("Invalid input: n and r must be non-negative integers, and r <= n")
else:
nPr = calculate_nPr(n, r)
nCr = calculate_nCr(n, r)
print(f"nPr: {nPr}")
print(f"nCr: {nCr}")
Output:
Enter the value of n: 10
Enter the value of r: 15
Invalid input: n and r must be non-negative integers, and r <= n
Q. 7 Write a program to print the sum of the followingseries1+1/2+1/3+….. +
1/n
def sum_series(n):
total_sum = 0
for i in range(1, n + 1):
total_sum += 1/i
return total_sum
n_terms = int(input("Enter the number of terms (n): "))
if n_terms<= 0:
print("Please enter a positive integer.")
else:
result = sum_series(n_terms)
print(f"The sum of the series up to {n_terms} terms is: {result}")
Output :
Enter the number of terms (n): 15
The sum of the series up to 15 terms is: 3.3182289932289937
Q. 8 Reverse words in a given String in Python
def reverse_words(s):
words = [Link]()
[Link]()
return ' '.join(words)
input_string = input("Enter a string: ")
reversed_string = reverse_words(input_string)
print(f"Reversed string: {reversed_string}")
Output:
Enter a string: Hello World Python
Reversed string: Python World Hello
Q. 9 Write Python code to multiply two matrices using nested loops and also Perform transpose of
the resultant matrix
defmultiply_matrices(matrix1, matrix2):
row1 = len(matrix1)
col1 = len(matrix1[0])
row2 = len(matrix2)
col2 = len(matrix2[0])
if col1 != row2:
return "Matrices cannot be multiplied"
result = [[0 for _ in range(col2)] for _ in range(row1)]
for i in range(row1):
for j in range(col2):
for k in range(col1):
result[i][j] += matrix1[i][k] * matrix2[k][j]
return result
def transpose_matrix(matrix):
rows = len(matrix)
cols = len(matrix[0])
transposed = [[0 for _ in range(rows)] for _ in range(cols)]
for i in range(rows):
for j in range(cols):
transposed[j][i] = matrix[i][j]
return transposed
# Example usage (user would input matrices in a real program)
# For simplicity, hardcoding example matrices here
mat1 = [[1, 2], [3, 4]]
mat2 = [[5, 6], [7, 8]]
multiplied = multiply_matrices(mat1, mat2)
if isinstance(multiplied, str):
print(multiplied)
else:
print("Multiplied matrix:")
for row in multiplied:
print(row)
transposed = transpose_matrix(multiplied)
print("Transposed matrix:")
for row in transposed:
print(row)
Output:
Multiplied matrix:
[19, 22]
[43, 50]
Transposed matrix:
[19, 43]
[22, 50]
Q.10Write Python program to sort words in a sentence in decreasing order of
their length Display the sorted words along with their length
def sort_words_by_length_desc(sentence):
words = [Link]()
[Link](key=len, reverse=True)
return words
input_sentence = input("Enter a sentence: ")
sorted_words = sort_words_by_length_desc(input_sentence)
print("Sorted words and their lengths:")
for word in sorted_words:
print(f"'{word}': {len(word)}")
Output:
Enter a sentence: Python program
Sorted words and their lengths:
'program': 7
'Python': 6
Q 11Write a function which receives a variable number of strings as
arguments. Find unique characters in each string.
def find_unique_characters(*strings):
unique_chars = {}
for s in strings:
chars = set(s)
unique_chars[s] = chars
return unique_chars
# Example usage
result = find_unique_characters("hello", "world", "python")
for string, chars in [Link]():
print(f"Unique characters in '{string}': {chars}")
Output:
Unique characters in 'hello': {'h', 'l', 'o', 'e'}
Unique characters in 'world': {'d', 'l', 'w', 'r', 'o'}
Unique characters in 'python': {'t', 'p', 'n', 'h', 'y', 'o'}
Q. 12Write a Python program that accepts an integer(n) and computes the
value of n+nn+nnn
def compute_nn_nnn(n):
n_str = str(n)
nn_str = n_str + n_str
nnn_str = n_str + n_str + n_str
result = n + int(nn_str) + int(nnn_str)
return result
num = int(input("Enter an integer (n): "))
value = compute_nn_nnn(num)
print(f"The value of n+nn+nnn is: {value}")
Output:
Enter an integer (n): 10
The value of n+nn+nnn is: 102030
Q. 13Python program to check whether the given integer is a multiple of 5
def is_multiple_of_5(number):
return number % 5 == 0
num = int(input("Enter an integer: "))
if is_multiple_of_5(num):
print(f"{num} is a multiple of 5.")
else:
print(f"{num} is not a multiple of 5.")
Output:
Enter an integer: 15
15 is a multiple of 5.
Q. 14Python program to check whether the given integer is a multiple of both
5 and7
def is_multiple_of_5_and_7(number):
return number % 5 == 0 and number % 7 == 0
num = int(input("Enter an integer: "))
if is_multiple_of_5_and_7(num):
print(f"{num} is a multiple of both 5 and 7.")
else:
print(f"{num} is not a multiple of both 5 and 7.")
Output:
Enter an integer: 35
35 is a multiple of both 5 and 7.
Q.15. Pythonprogramtodisplayallintegerswithintherange100-200whosesum
of digits is an even number
def sum_of_digits_is_even(number):
s = str(number)
digit_sum = 0
for digit in s:
digit_sum += int(digit)
return digit_sum % 2 == 0
print("Integers between 100 and 200 whose sum of digits is an even number:")
for i in range(100, 201):
if sum_of_digits_is_even(i):
print(i)
Output:
Integers between 100 and 200 whose sum of digits is an even number:
101
103
105
107
109
110
112
114
116
118
121
123
125
127
129
130
132
134
136
138
141
143
145
147
149
150
152
154
156
158
161
163
165
167
169
170
172
174
176
178
181
183
185
187
189
190
192
194
196
198
200