python interview question
python interview question
Coding Questions
Write a Python program to reverse a string.
def reverse_string(s):
return s[::-1]
print(reverse_string("Python"))
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))
print(max(lst))
a, b = 0, 1
for _ in range(n):
print(a, end=" ")
a, b = b, a + b
fibonacci(5)
def fibonacci(n):
a, b = 0, 1
for _ in range(n):
a, b = b, a + b
fibonacci(5)
OOPs in Python
File Handling
How do you read/write a file in Python?
python
Copy code
with open("file.txt", "r") as file:
data = file.read()
with open("file.txt", "w") as file:
file.write("Hello!")
31.
32. Explain modes in Python file handling.
○ Answer: r (read), w (write), a (append), rb/wb (binary).
How to check if a file exists?
python
Copy code
import os
print(os.path.exists("file.txt"))
33.
34.
35. What is the difference between read() and readlines()?
○ Answer: read() returns the entire content as a string, while readlines()
returns a list of lines.
Miscellaneous
Answer: A set stores unique items, while a dictionary stores key-value pairs.