Q: How do you print 'Hello, World!' in Python?
print("Hello, World!")
Q: How do you take user input and display it?
name = input("Enter your name: ")
print("Hello,", name)
Q: How do you check if a number is even or odd?
num = int(input("Enter a number: "))
if num % 2 == 0:
print("Even")
else:
print("Odd")
Q: How do you find the factorial of a number using recursion?
def factorial(n):
if n == 0:
return 1
return n * factorial(n - 1)
print(factorial(5)) # Output: 120
Q: What is a list comprehension? Give an example.
squares = [x**2 for x in range(1, 6)]
print(squares) # Output: [1, 4, 9, 16, 25]
Q: How to reverse a string in Python?
s = "hello"
print(s[::-1]) # Output: "olleh"
Q: What is a lambda function? Give an example.
add = lambda x, y: x + y
print(add(3, 5)) # Output: 8
Q: How do you handle exceptions in Python?
try:
result = 10 / 0
except ZeroDivisionError:
print("Cannot divide by zero.")
finally:
print("Done.")
Q: How do you read and write to a file?
# Writing
with open("example.txt", "w") as f:
f.write("Hello file!")
# Reading
with open("example.txt", "r") as f:
content = f.read()
print(content)