Python Practice Questions & Answers
Q1: Print 'Hello, World!'
print("Hello, World!")
Q2: Swap two numbers without using a third variable
a, b = 5, 10
a, b = b, a
print(a, b) # Output: 10 5
Q3: Check if a number is even or odd
num = int(input('Enter a number: '))
if num % 2 == 0:
print('Even')
else:
print('Odd')
Q4: Reverse a list without using reverse()
lst = [1, 2, 3, 4, 5]
print(lst[::-1]) # Output: [5, 4, 3, 2, 1]
Q5: Find the sum of all elements in a list
numbers = [10, 20, 30, 40]
print(sum(numbers)) # Output: 100
Q6: Print numbers from 1 to 10 using a loop
for i in range(1, 11):
print(i)
Q7: Check if a string is a palindrome
s = 'madam'
if s == s[::-1]:
print('Palindrome')
else:
print('Not a palindrome')
Q8: Count the vowels in a string
s = 'Hello World'
count = sum(1 for c in s.lower() if c in 'aeiou')
print(count) # Output: 3
Q9: Function to find factorial of a number
def factorial(n):
return 1 if n == 0 else n * factorial(n-1)
print(factorial(5)) # Output: 120
Q10: Function to check if a number is prime
def is_prime(n):
if n < 2:
return False
for i in range(2, int(n**0.5) + 1):
if n % i == 0:
return False
return True
print(is_prime(11)) # Output: True
Q11: Create a dictionary and access values
student = {'name': 'John', 'age': 21, 'course': 'Python'}
print(student['name']) # Output: John
Q12: Convert two lists into a dictionary
keys = ['name', 'age', 'city']
values = ['Alice', 25, 'New York']
dictionary = dict(zip(keys, values))
print(dictionary)
Q13: Write a Python class and create an object
class Car:
def __init__(self, brand, model):
self.brand = brand
self.model = model
def display(self):
print(f'Car: {self.brand} {self.model}')
c = Car('Toyota', 'Camry')
c.display()
Q14: Read a file and print its content
with open('sample.txt', 'r') as file:
print(file.read())
Q15: Implement a queue using a list
queue = []
queue.append(1)
queue.append(2)
queue.append(3)
print(queue.pop(0)) # Output: 1
Q16: Find the largest element in a list
numbers = [10, 50, 20, 80, 30]
print(max(numbers)) # Output: 80