0% found this document useful (0 votes)
1 views28 pages

Python Interview Questions

The document provides a comprehensive overview of Python programming concepts, including platform independence, differences between data types (lists vs. tuples), typecasting, operators, conditional statements, and loops. It also includes examples and explanations of various programming tasks such as checking even or odd numbers, finding the largest of three numbers, and implementing a simple calculator. Overall, it serves as a guide for understanding fundamental Python programming principles and syntax.

Uploaded by

likhitha0324
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1 views28 pages

Python Interview Questions

The document provides a comprehensive overview of Python programming concepts, including platform independence, differences between data types (lists vs. tuples), typecasting, operators, conditional statements, and loops. It also includes examples and explanations of various programming tasks such as checking even or odd numbers, finding the largest of three numbers, and implementing a simple calculator. Overall, it serves as a guide for understanding fundamental Python programming principles and syntax.

Uploaded by

likhitha0324
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 28

PYTHON

1.what is platform independent model in python?

2.difference between source and interactive mode in python?


-in source mode programmer needs to save the file with .py extension
-in interactive mode line by line execution will be done

3.what are python comments?


-single line comment(#)
-multi line comment(denoted with pair of triple quotes)

1. What is the difference between a list and a tuple?​


Answer:

●​ list is mutable (can be changed), while tuple is immutable.​

●​ Lists use more memory and are slower than tuples.​

●​ Tuples can be used as dictionary keys, lists cannot.​

2. What is the difference between is and == in Python?​


Answer:

●​ == compares values.​

●​ is compares object identity (i.e., whether two variables point to the same object
in memory).​

3. How is a Python string different from a list?​


Answer:

●​ Strings are immutable; lists are mutable.​


●​ Strings store sequences of characters; lists can store elements of different types.​

4. What is the output of type([]) and type(())?​


Answer:

●​ type([]) returns <class 'list'>​

●​ type(()) returns <class 'tuple'>​

6. Explain Python’s dict datatype.​


Answer:

●​ dict is an ordered collection of key-value pairs.​

●​ Keys must be unique and immutable; values can be any type.​

●​ Example: {'name': 'Alice', 'age': 30}​

7. What is the difference between mutable and immutable datatypes in Python?​


Answer:

●​ Mutable: Can be changed after creation (list, dict, set, bytearray)​

●​ Immutable: Cannot be changed after creation (int, float, str, tuple,


frozenset, bytes)​

9. Can a dictionary key be a list? Why or why not?​


Answer:​
No, because list is mutable and . Dictionary keys must be immutable and hashable
types like str, int, tuple.

10. What are Python’s numeric types, and when would you use each?​
Answer:

●​ int: Whole numbers​

●​ float: Decimal numbers​

●​ complex: Numbers with real and imaginary parts (e.g., 3 + 4j)​


Use int for counting, float for scientific or financial calculations, and
complex for mathematical applications involving imaginary numbers.​

1. What is typecasting in Python?

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

2. What are the two types of typecasting in Python?

Answer:

●​ Implicit Typecasting: Done automatically by Python.​

●​ Explicit Typecasting: Done manually by the programmer using built-in functions.​


3. What is implicit typecasting? Give an example.

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

4. What is explicit typecasting? Give an example.

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

5. What happens when you try to cast a non-numeric string to an int?

Answer:​
It raises a ValueError.

Example:

int("abc") # Raises ValueError: invalid literal for int()

6. How do you convert a list to a tuple and vice versa?

Answer:
●​ List to tuple: tuple([1, 2, 3])​

●​ Tuple to list: list((1, 2, 3))​

7. Can you typecast a float to a string? How?

Answer:​
Yes. Use str() function.

Example:

f = 3.14
s = str(f) # "3.14"

8. Can you convert a dictionary to a list? What gets converted?

Answer:​
Yes. Converting a dictionary to a list returns its keys by default.

Example:

d = {'a': 1, 'b': 2}
list(d) # ['a', 'b']

9. How do you convert a string to a list of characters or words?

Answer:

●​ Characters: list("hello") → ['h', 'e', 'l', 'l', 'o']​

●​ Words: "hello world".split() → ['hello', 'world']​


11. Can you convert a string to a complex number in Python?

Answer:​
Yes, using the complex() function.

Example:

complex("3+4j") # Output: (3+4j)

12. What happens if you try to cast a list to an int?

Answer:​
It raises a TypeError because Python cannot directly convert a list to an integer.

Example:

int([1, 2, 3]) # TypeError

DATE : 05/07/2025

1. What are the different types of operators in Python?

Answer:​
Python provides the following types of operators:

1.​ Arithmetic Operators: +, -, *, /, //, %, **​

2.​ Comparison (Relational) Operators: ==, !=, >, <, >=, <=​

3.​ Assignment Operators: =, +=, -=, *=, /=, etc.​

4.​ Logical Operators: and, or, not​


5.​ Bitwise Operators: &, |, ^, ~, <<, >>​

6.​ Membership Operators: in, not in​

7.​ Identity Operators: is, is not​

2. What is the difference between == and is in Python?

Answer:

●​ == checks value equality (do the values match?).​

●​ 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

3. What is the output of 3 / 2, 3 // 2, and 3 % 2?

Answer:

3 / 2 # 1.5 (true division)


3 // 2 # 1 (floor division)
3 % 2 # 1 (modulo - remainder)

4. What does the ** operator do in Python?


Answer:​
It performs exponentiation.

Example:

2 ** 3 # 8

6. Explain the use of the in and not in operators.

Answer:​
They are membership operators used to check if a value exists in a sequence (like
list, tuple, string).

Example:

'a' in 'apple' # True


10 not in [1, 2, 3] # True

7. What is the difference between & and and, | and or?

Answer:

●​ & and | are bitwise operators.​

●​ and and or are logical operators.​

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)

10. How do assignment operators like +=, *=, etc., work?

Answer:​
They update the value of a variable in place.

Example:

x = 5
x += 2 # x = x + 2 → x becomes 7

14. What does the >> and << operators do?

Answer:​
They are bitwise shift operators:

●​ << shifts bits to the left (multiplies by 2)​

●​ >> shifts bits to the right (divides by 2)​

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.

2. What is the syntax of an if statement in Python?

Answer:

if condition:
# block of code

Example:

python
CopyEdit
x = 10
if x > 5:
print("x is greater than 5")

3. What is the difference between if, elif, and else?

Answer:

●​ if: Executes when the condition is True​

●​ elif: Checks another condition if previous if or elif is False​

●​ else: Executes when all previous conditions are False​

Example:

x = 20
if x < 10:
print("Less than 10")
elif x < 30:
print("Less than 30")
else:
print("30 or more")

4. Can we have multiple elif blocks in a conditional structure?

Answer:​
Yes. You can use multiple elif blocks, but only one else block (optional), and one
if.

5. Is elif mandatory in conditional statements?

Answer:​
No. You can use only if, or if with else. elif is optional.

6. What is indentation and why is it important in conditional blocks?

Answer:​
Python uses indentation (whitespace) to define code blocks. Incorrect indentation leads
to IndentationError.

Example:

if True:
print("Correctly indented") # Required

7. What is a nested if statement?

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")

8. Can we use logical operators (and, or, not) in conditions?

Answer:​
Yes.

Example:

x = 5
if x > 0 and x < 10:
print("x is a single-digit positive number")

9. What is the output of this code?


x = 0
if x:
print("True")
else:
print("False")

Answer:​
False​
Because 0 is evaluated as False in a boolean context.

10. What types of expressions can be used in if conditions?


Answer:​
Any expression that evaluates to a Boolean (True or False) — including
comparisons, function calls, logical operations, or variables.

11.Check if a Number is Even or Odd

Question:​
Write a program to check whether a number is even or odd.

Answer:

num = int(input("Enter a number: "))

if num % 2 == 0:

print("Even")

else:

print("Odd")

2. Find the Largest of Three Numbers

Question:​
Write a program to find the largest among three numbers.

Answer:

a = 10

b = 25

c = 15

if a >= b and a >= c:


print("Largest:", a)

elif b >= a and b >= c:

print("Largest:", b)

else:

print("Largest:", c)

3. Check if a Year is a Leap Year

Question:​
Check whether a year is a leap year or not.

Answer:

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")

4. Grade Calculator Using Marks

Question:​
Write a program to assign grades based on marks:
●​ >=90: A​

●​ >=80: B​

●​ >=70: C​

●​ >=60: D​

●​ Else: F​

Answer:

marks = int(input("Enter marks: "))

if marks >= 90:

print("Grade: A")

elif marks >= 80:

print("Grade: B")

elif marks >= 70:

print("Grade: C")

elif marks >= 60:

print("Grade: D")

else:

print("Grade: F")

5. Check if a Number is Positive, Negative, or Zero


Question:​
Write a program to check if a number is positive, negative, or zero.

Answer:

num = float(input("Enter a number: "))

if num > 0:

print("Positive")

elif num < 0:

print("Negative")

else:

print("Zero")

6. Determine Eligibility to Vote

Question:​
Write a program to check if a person is eligible to vote (age ≥ 18).

Answer:

age = int(input("Enter your age: "))

if age >= 18:

print("Eligible to vote")

else:

print("Not eligible to vote")


7. Check if a Character is a Vowel or Consonant

Question:​
Write a program to check whether an alphabet is a vowel or a consonant.

Answer:

ch = input("Enter a character: ").lower()

if ch in 'aeiou':

print("Vowel")

elif ch.isalpha():

print("Consonant")

else:

print("Not an alphabet")

9. Simple Calculator Using if-elif-else

Question:​
Build a basic calculator that performs +, -, *, / operations.

Answer:

a = float(input("Enter first number: "))

b = float(input("Enter second number: "))

op = input("Enter operator (+, -, *, /): ")


if op == '+':

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:

print("Cannot divide by zero")

else:

print("Invalid operator")

✅ 10. Check if a Number is in a Given Range


Question:​
Write a program to check whether a number is within a given range (e.g., 1 to 100).

Answer:

num = int(input("Enter a number: "))

if 1 <= num <= 100:


print("Within range")

else:

print("Out of range")

1. What is the difference between for and while loops in Python?

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.

# for loop example


for i in range(5):
print(i)

# while loop example


i = 0
while i < 5:
print(i)
i += 1

2. What is an infinite loop? Give an example.

Answer:​
An infinite loop runs forever until it’s manually stopped. This typically occurs if the loop
condition never becomes False.

# Infinite while loop


while True:
print("Running forever")
3. How does range() work in a for loop?

Answer:​
range(start, stop, step) generates a sequence of numbers from start to
stop - 1, with an optional step.

for i in range(1, 6, 2):


print(i) # Output: 1, 3, 5

4. How do you exit a loop prematurely in Python?

Answer:​
Use the break statement to exit a loop before it naturally finishes.

for i in range(10):
if i == 5:
break
print(i)

5. How do you skip an iteration in a loop?

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

6. Can we use else with loops in Python? Explain with an example.

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

7. What will be the output of the following code?


i = 0
while i < 3:
print(i)
i += 1
else:
print("Done")

Answer:

0
1
2
Done

The else block runs after the while loop completes normally.

8. Write a loop to check if a number is prime.

Answer:
num = 13
is_prime = True

for i in range(2, int(num ** 0.5) + 1):


if num % i == 0:
is_prime = False
break

print("Prime" if is_prime else "Not Prime")

9. What is the output of nested loops like this?


for i in range(2):
for j in range(2):
print(i, j)

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.

11. Write a loop that prints the Fibonacci sequence up to N terms.


n = 10
a, b = 0, 1
for _ in range(n):
print(a, end=" ")
a, b = b, a + b
12. Use a while loop to reverse a number.
num = 1234
rev = 0
while num != 0:
rev = rev * 10 + num % 10
num //= 10
print(rev) # Output: 4321

13. Explain the difference between pass, break, and continue with examples.

Statemen Description Example


t

pass Does nothing, if x: pass


placeholder

break Exits loop if x == 5:


break

continu Skips current iteration if x == 5:


e continue

1. What is exception handling in Python?

Answer:​
Exception handling is the process of responding to unexpected errors during
program execution. Python uses try, except, and finally blocks to handle
exceptions.

2. What are the keywords used in exception handling?

Answer:

●​ try: Block of code to test for errors.​


●​ except: Block of code that handles the error.​

●​ finally: Executes code regardless of what happens in the try.​

3. Give an example of basic exception handling.


try:
x = 10 / 0
except ZeroDivisionError:
print("Cannot divide by zero!")

4. What is the difference between syntax errors and exceptions?

Answer:

●​ Syntax Error: Detected during parsing (before the program runs).​

●​ Exception: Raised during program execution (runtime).

6. What is the purpose of the finally block?

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).

1. What is a function in Python?​


Answer:​
A function in Python is a block of reusable code that performs a specific task. It is
defined using the def keyword.

def greet(name):
return f"Hello, {name}!"

2. What is the difference between a function and a method?​


Answer:

●​ A function is independent and can be called on its own.​

●​ A method is a function that is associated with an object (typically called on an


object).

# Function
def add(a, b):
return a + b

# Method
s = "hello"
s.upper() # upper is a string method

3. How do you define a function in Python?​


Answer:

def function_name(parameters):
# code block
return result

Example:

def square(x):
return x * x

4. What is the use of the return statement in a function?​


Answer:​
The return statement ends the function and optionally returns a value.

def add(a, b):


return a + b

**5. What are *args and kwargs in Python functions?​


Answer:

●​ *args allows passing a variable number of positional arguments.​

●​ **kwargs allows passing a variable number of keyword arguments.

def example(*args, **kwargs):


print(args) # Tuple of positional arguments
print(kwargs) # Dict of keyword arguments

7. What are default arguments in Python?​


Answer:​
Default arguments allow a function to assume a default value if a value is not provided.

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:

●​ Local scope: inside the function.​

●​ Global scope: outside all functions.​

●​ 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

10. Using *args

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

You might also like