Python Interview Questions and Answers
Python Interview Questions and Answers
• Compilation: When you write Python code and run it, the source code (.py files)
is first compiled into an intermediate form called bytecode (.pyc files). This
bytecode is a lower-level representation of your code, but it is still not directly
machine code. It’s something that the Python Virtual Machine (PVM) can
understand and execute.
Some implementations, like PyPy, use Just-In-Time (JIT) compilation, where Python
code is compiled into machine code at runtime for faster execution, blurring the lines
between interpretation and compilation.
We can concatenate two lists in Python using the +operator or the extend() method.
a = [1, 2, 3]
b = [4, 5, 6]
res = a + b
print(res)
Output
[1, 2, 3, 4, 5, 6]
a = [1, 2, 3]
b = [4, 5, 6]
a.extend(b)
print(a)
Output
[1, 2, 3, 4, 5, 6]
• For loop: Used when we know how many times to repeat, often with lists, tuples,
sets, or dictionaries.
• While loop: Used when we only have an end condition and don’t know exactly
how many times it will repeat.
for i in range(5):
print(i)
c=0
while c < 5:
print(c)
c += 1
To floor a number in Python, you can use the math.floor() function, which returns the
largest integer less than or equal to the given number.
• floor() method in Python returns the floor of x i.e., the largest integer not greater
than x.
• Also, The method ceil(x) in Python returns a ceiling value of x i.e., the smallest
integer greater than or equal to x.
import math
n = 3.7
F_num = math.floor(n)
print(F_num)
Output
Yes, Several arguments can be passed to a function, including objects, variables (of the
same or distinct data types) and functions. Functions can be passed as parameters to
other functions because they are objects. Higher-order functions are functions that can
take other functions as arguments.
return x + y
return func(a, b)
print(apply_func(add, 3, 5))
• Statically typed languages are usually faster to execute due to type checking at
compile time.
Example:
x = 10 # x is an integer
Here, the type of x changes at runtime based on the assigned value hence it shows
dynamic nature of Python.
def fun():
fun()
Here, fun() does nothing, but the code stays syntactically correct.
• Depending on the type of object you pass in the function, the function behaves
differently. Immutable objects show “pass by value” whereas mutable objects
show “pass by reference”.
You can check the difference between pass-by-value and pass-by-reference in the
example below:
def call_by_val(x):
x=x*2
return
def call_by_ref(b):
b.append("D")
return
a = ["E"]
num = 6
call_by_val(num)
call_by_ref(a)
Output
value updated to 12
A lambda function is an anonymous function. This function can have any number of
parameters but, can have just one statement.
s1 = 'GeeksforGeeks'
print(s2(s1))
Output
GEEKSFORGEEKS