Python Interview Questions
Python Interview Questions
● == compares values.
● is compares object identity (i.e., whether two variables point to the same object
in memory).
10. What are Python’s numeric types, and when would you use each?
Answer:
Answer:
Typecasting is the process of converting one data type into another. In Python, it's also
known as type conversion.
Example:
x = "10"
y = int(x) # typecasting string to integer
Answer:
Answer:
Python automatically converts one data type to another without user intervention.
Example:
x = 10 # int
y = 2.5 # float
z = x + y # Python implicitly converts int to float
print(z) # Output: 12.5
Answer:
The programmer manually converts one type to another using functions like int(),
float(), str(), etc.
Example:
a = "123"
b = int(a) # Explicit typecasting from str to int
Answer:
It raises a ValueError.
Example:
Answer:
● List to tuple: tuple([1, 2, 3])
Answer:
Yes. Use str() function.
Example:
f = 3.14
s = str(f) # "3.14"
Answer:
Yes. Converting a dictionary to a list returns its keys by default.
Example:
d = {'a': 1, 'b': 2}
list(d) # ['a', 'b']
Answer:
Answer:
Yes, using the complex() function.
Example:
Answer:
It raises a TypeError because Python cannot directly convert a list to an integer.
Example:
DATE : 05/07/2025
Answer:
Python provides the following types of operators:
2. Comparison (Relational) Operators: ==, !=, >, <, >=, <=
Answer:
● is checks identity (do both variables point to the same object in memory?).
Example:
a = [1, 2]
b = [1, 2]
a == b # True
a is b # False
Answer:
Example:
2 ** 3 # 8
Answer:
They are membership operators used to check if a value exists in a sequence (like
list, tuple, string).
Example:
Answer:
Example:
# Bitwise
5 & 3 # 1 (binary: 101 & 011 = 001)
5 | 3 # 7 (binary: 101 | 011 = 111)
# Logical
True and False # False
True or False # True
9. What does the ~ operator do?
Answer:
It is a bitwise NOT operator. It inverts all the bits.
Example:
~5 # -6 (because ~x = -x - 1)
Answer:
They update the value of a variable in place.
Example:
x = 5
x += 2 # x = x + 2 → x becomes 7
Answer:
They are bitwise shift operators:
Example:
4 << 1 # 8
4 >> 1 # 2
1. What are conditional statements in Python?
Answer:
Conditional statements are used to perform different actions based on different
conditions using keywords like if, elif, and else.
Answer:
if condition:
# block of code
Example:
python
CopyEdit
x = 10
if x > 5:
print("x is greater than 5")
Answer:
Example:
x = 20
if x < 10:
print("Less than 10")
elif x < 30:
print("Less than 30")
else:
print("30 or more")
Answer:
Yes. You can use multiple elif blocks, but only one else block (optional), and one
if.
Answer:
No. You can use only if, or if with else. elif is optional.
Answer:
Python uses indentation (whitespace) to define code blocks. Incorrect indentation leads
to IndentationError.
Example:
if True:
print("Correctly indented") # Required
Answer:
An if block inside another if block is called a nested if.
Example:
x = 15
if x > 10:
if x < 20:
print("Between 10 and 20")
Answer:
Yes.
Example:
x = 5
if x > 0 and x < 10:
print("x is a single-digit positive number")
Answer:
False
Because 0 is evaluated as False in a boolean context.
Question:
Write a program to check whether a number is even or odd.
Answer:
if num % 2 == 0:
print("Even")
else:
print("Odd")
Question:
Write a program to find the largest among three numbers.
Answer:
a = 10
b = 25
c = 15
print("Largest:", b)
else:
print("Largest:", c)
Question:
Check whether a year is a leap year or not.
Answer:
print("Leap Year")
else:
Question:
Write a program to assign grades based on marks:
● >=90: A
● >=80: B
● >=70: C
● >=60: D
● Else: F
Answer:
print("Grade: A")
print("Grade: B")
print("Grade: C")
print("Grade: D")
else:
print("Grade: F")
Answer:
if num > 0:
print("Positive")
print("Negative")
else:
print("Zero")
Question:
Write a program to check if a person is eligible to vote (age ≥ 18).
Answer:
print("Eligible to vote")
else:
Question:
Write a program to check whether an alphabet is a vowel or a consonant.
Answer:
if ch in 'aeiou':
print("Vowel")
elif ch.isalpha():
print("Consonant")
else:
print("Not an alphabet")
Question:
Build a basic calculator that performs +, -, *, / operations.
Answer:
print("Result:", a + b)
elif op == '-':
print("Result:", a - b)
elif op == '*':
print("Result:", a * b)
elif op == '/':
if b != 0:
print("Result:", a / b)
else:
else:
print("Invalid operator")
Answer:
else:
print("Out of range")
Answer:
● for loop is used for iterating over a sequence (like a list, tuple, dictionary, set,
or string).
● while loop is used when you want to repeat a block of code as long as a
condition is true.
Answer:
An infinite loop runs forever until it’s manually stopped. This typically occurs if the loop
condition never becomes False.
Answer:
range(start, stop, step) generates a sequence of numbers from start to
stop - 1, with an optional step.
Answer:
Use the break statement to exit a loop before it naturally finishes.
for i in range(10):
if i == 5:
break
print(i)
Answer:
Use the continue statement to skip the current iteration and continue with the next.
for i in range(5):
if i == 2:
continue
print(i) # Skips 2
Answer:
Yes. The else block runs only if the loop completes without a break.
for i in range(5):
if i == 3:
break
print(i)
else:
print("Completed without break")
# Output:
# 0
# 1
# 2
Answer:
0
1
2
Done
The else block runs after the while loop completes normally.
Answer:
num = 13
is_prime = True
Answer:
0 0
0 1
1 0
1 1
This is a nested loop, where the inner loop runs fully for each outer loop iteration.
13. Explain the difference between pass, break, and continue with examples.
Answer:
Exception handling is the process of responding to unexpected errors during
program execution. Python uses try, except, and finally blocks to handle
exceptions.
Answer:
Answer:
Answer:
The finally block always runs, regardless of whether an exception occurred.
Useful for cleanup actions like closing files or database connections.
try:
f = open("file.txt")
# some operations
except FileNotFoundError:
print("File not found")
finally:
print("This runs no matter what")
9. What happens if you don't handle an exception?
Answer:
If not handled, Python terminates the program and prints a traceback (stack trace).
def greet(name):
return f"Hello, {name}!"
# Function
def add(a, b):
return a + b
# Method
s = "hello"
s.upper() # upper is a string method
def function_name(parameters):
# code block
return result
Example:
def square(x):
return x * x
def greet(name="Guest"):
return f"Hello, {name}!"
8. What is the scope of a variable in Python functions?
Answer:
Scope defines where a variable can be accessed:
● Nonlocal: used to modify a variable in the nearest enclosing scope that’s not
global.
def outer():
x = "outer"
def inner():
nonlocal x
x = "inner"
9. Write a function that returns the power of a number. The default power is 2.
def power(num, exponent=2):
return num ** exponent
# Test
print(power(3)) # Output: 9
print(power(3, 3)) # Output: 27
Q: Write a function that accepts any number of numerical arguments and returns their
sum.
def sum_all(*args):
return sum(args)
# Test
print(sum_all(1, 2, 3)) # Output: 6
print(sum_all(10, 20, 30, 40)) # Output: 100