Answers of Python Practical Questions
Python Programming
1. Factorial of a number
num = int(input("Enter a number: "))
result = 1
for i in range(1, num + 1):
result *= i
print("Factorial:", result)
2. Check if a number is prime
num = int(input("Enter a number: "))
if num > 1:
for i in range(2, int(num ** 0.5) + 1):
if num % i == 0:
print("Not a prime")
break
else:
print("Prime number")
else:
print("Not a prime")
3. Print 1 to n natural numbers using while loop
n = int(input("Enter n: "))
i=1
while i <= n:
print(i)
i += 1
4. Check if a number is even or odd
num = int(input("Enter a number: "))
if num % 2 == 0:
print("Even")
else:
print("Odd")
5. Check if a year is leap year or not
year = int(input("Enter year: "))
if (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0):
print("Leap year")
else:
print("Not a leap year")
6. Sum of digits of a number
num = int(input("Enter a number: "))
total = 0
while num > 0:
total += num % 10
num //= 10
print("Sum of digits:", total)
7. Swap two numbers without using third variable
a = int(input("Enter first number: "))
b = int(input("Enter second number: "))
a, b = b, a
print("a:", a, "b:", b)
8. Sum of numbers from 1 to n using for loop
n = int(input("Enter n: "))
total = 0
for i in range(1, n+1):
total += i
print("Sum:", total)
9. Fibonacci series up to n terms
n = int(input("How many terms? "))
a, b = 0, 1
for _ in range(n):
print(a, end=' ')
a, b = b, a + b
10. Reverse a string entered by the user
s = input("Enter a string: ")
print("Reversed:", s[::-1])
11. Check palindrome string
s = input("Enter a string: ")
if s == s[::-1]:
print("Palindrome")
else:
print("Not a palindrome")
12. Create an array using NumPy
import numpy as np
arr = np.array([1, 2, 3, 4, 5])
print(arr)
13. Sequential 1D array with multiples of 10 from 10 to 100
import numpy as np
arr = np.arange(10, 101, 10)
print(arr)
14. 3x4 array with random integers less than 10
import numpy as np
arr = np.random.randint(0, 10, (3, 4))
print(arr)
15. 2D array of size 4x4 with values 1 to 16
import numpy as np
arr = np.arange(1, 17).reshape(4, 4)
print(arr)
16. Add two NumPy arrays element-wise
import numpy as np
arr1 = np.array([1, 2, 3])
arr2 = np.array([4, 5, 6])
result = arr1 + arr2
print(result)
17. Maximum and minimum values in a NumPy array
import numpy as np
arr = np.array([5, 3, 8, 1, 6])
print("Max:", arr.max())
print("Min:", arr.min())