Python Interview Questions and Answers (For Freshers)
1. Swap two numbers without using a third variable
a = 5
b = 10
a, b = b, a
print(a, b) # Output: 10 5
2. Check if a number is prime
def is_prime(n):
if n <= 1:
return False
for i in range(2, int(n**0.5)+1):
if n % i == 0:
return False
return True
print(is_prime(7)) # True
3. Generate Fibonacci series up to n terms
def fibonacci(n):
a, b = 0, 1
for _ in range(n):
print(a, end=' ')
a, b = b, a + b
fibonacci(5) # Output: 0 1 1 2 3
4. Check if a string is a palindrome
def is_palindrome(s):
return s == s[::-1]
print(is_palindrome('madam')) # True
5. Find second largest element in a list
def second_largest(nums):
first = second = float('-inf')
for num in nums:
if num > first:
second = first
first = num
elif first > num > second:
second = num
return second
print(second_largest([4, 1, 3, 2])) # Output: 3
6. Check if two strings are anagrams
def is_anagram(str1, str2):
return sorted(str1) == sorted(str2)
print(is_anagram('listen', 'silent')) # True
7. Reverse words in a sentence
s = 'hello world'
print(' '.join(s.split()[::-1])) # Output: 'world hello'
8. Read a file and count words
with open('file.txt', 'r') as f:
text = f.read()
words = text.split()
print(len(words))
9. Create a class with inheritance
class Animal:
def speak(self):
return 'Sound'
class Dog(Animal):
def speak(self):
return 'Bark'
d = Dog()
print(d.speak()) # Output: Bark
10. Handle divide-by-zero error
try:
a = 5 / 0
except ZeroDivisionError:
print("Can't divide by zero")