Python Examples
Question 1:
Write a Python program that takes a number and checks if it is positive.
def check_positive(number):
if number > 0:
return "The number is positive."
elif number == 0:
return "The number is zero."
else:
return "The number is negative."
if __name__ == "__main__":
num = float(input("Enter a number: "))
result = check_positive(num)
print(result)
Question 2:
Write a Python program that checks whether a given number is even or odd.
def check_even_odd(number):
if number % 2 == 0:
return "The number is even."
else:
return "The number is odd."
if __name__ == "__main__":
num = int(input("Enter a number: "))
result = check_even_odd(num)
print(result)
Question 3:
Write a Python program that assigns a grade based on the following criteria:
90 and above → Grade A
80 to 89 → Grade B
70 to 79 → Grade C
Below 70 → Grade D
def assign_grade(score):
if score >= 90:
return "Grade A"
elif score >= 80:
return "Grade B"
elif score >= 70:
return "Grade C"
else:
return "Grade D"
if __name__ == "__main__":
score = float(input("Enter the score: "))
grade = assign_grade(score)
print(grade)
Question 4:
Write a Python program that prints numbers from 1 to 5 using a for loop.
for i in range(1, 6):
print(i)
OR:
num = 1
while num <= 5:
print(num)
num += 1
Question 5:
Write a for loop that prints even numbers from 2 to 10.
for i in range(2, 11, 2):
print(i)
OR:
num = 2
while num <= 10:
print(num)
num += 2
Question 6:
Write a Python program that prints each character of the string "Python" using a for loop.
word = "Python"
for char in word:
print(char)
OR:
word = "Python"
i = 0
while i < len(word):
print(word[i])
i += 1
Question 7:
Write a Python program that prints each item from the list fruits = ["apple", "banana",
"cherry"] .
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
OR:
fruits = ["apple", "banana", "cherry"]
i = 0
while i < len(fruits):
print(fruits[i])
i += 1
Question 8:
Write a for loop to calculate the sum of numbers from 1 to 10.
total = 0
for i in range(1, 11):
total += i
print("Sum:", total)
OR:
total = 0
i = 1
while i <= 10:
total += i
i += 1
print("Sum:", total)
Question 9:
Write a Python program that calculates the sum of the digits of the number 12345 using a
while loop.
num = 12345
sum_digits = 0
while num > 0:
sum_digits += num % 10 # Get last digit
num //= 10 # Remove last digit
print("Sum of digits:", sum_digits)
Question 10:
Write a Python function factorial that takes a number and returns its factorial.
def factorial(n):
result = 1
for i in range(1, n + 1):
result *= i
return result
print("Factorial of 5:", factorial(5))
Question 11:
Write a Python function is_palindrome that checks if a given string is a palindrome (reads the
same forward and backward).
def is_palindrome(text):
return text == text[::-1]
print(is_palindrome("madam")) # Output: True
print(is_palindrome("hello")) # Output: False
Question 12:
Write a Python function find_max that takes a list of numbers and returns the maximum value.
def find_max(numbers):
max_num = numbers[0]
for num in numbers:
if num > max_num:
max_num = num
return max_num
numbers = [3, 7, 2, 9, 5]
print("Maximum number:", find_max(numbers))
Question 13:
Write a Python function get_even_numbers that takes a list and returns a new list containing
only even numbers.
def get_even_numbers(lst):
even_numbers = [num for num in lst if num % 2 == 0]
return even_numbers
numbers = [1, 2, 3, 4, 5, 6]
print(get_even_numbers(numbers)) # Output: [2, 4, 6]
Question 14:
Write a Python class Person with attributes name and age . Create an object and print its
details.
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def display_info(self):
print("Name: {}, Age: {}".format(self.name, self.age))
# Creating an object
person1 = Person("Ahmed", 20)
person1.display_info()
Question 15:
Write a Python class Car with attributes brand and year . Add a method display_car() to
print car details.
class Car:
def __init__(self, brand, year):
self.brand = brand
self.year = year
def display_car(self):
print("Car Brand: {}, Year: {}".format(self.brand, self.year))
car1 = Car("Toyota", 2022)
car1.display_car()
Question 16:
Write a Python class BankAccount with a private attribute _balance and methods to deposit
and withdraw money.
class BankAccount:
def __init__(self, balance):
self._balance = balance # Private attribute
def deposit(self, amount):
self._balance += amount
print(f"Deposited: {amount}, New Balance: {self._balance}")
def withdraw(self, amount):
if amount <= self._balance:
self._balance -= amount
print(f"Withdrew: {amount}, New Balance: {self._balance}")
else:
print("Insufficient balance!")
account = BankAccount(1000)
account.deposit(500)
account.withdraw(300)
account.withdraw(1500) # Should print "Insufficient balance!"
Question 17:
Write a Python class Student that inherits from Person and adds a grade attribute.
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def display_info(self):
print(f"Name: {self.name}, Age: {self.age}")
class Student(Person):
def __init__(self, name, age, grade):
super().__init__(name, age)
self.grade = grade
def display_student(self):
print(f"Name: {self.name}, Age: {self.age}, Grade: {self.grade}")
student1 = Student("Ali", 20, "A")
student1.display_student()
Question 18:
Write a Python class Book with attributes title and author . Use the __str__ method to
print book details.
class Book:
def __init__(self, title, author):
self.title = title
self.author = author
def __str__(self):
return f"Book: {self.title}, Author: {self.author}"
book1 = Book("Python Basics", "John Doe")
print(book1)
Question 19: Create an iterator class that returns numbers
starting from 1, increasing by 1 each time, up to a limit.
Write a Python class MyNumbers that acts as an iterator, returning numbers from 1 to a given
limit.
class MyNumbers:
def __init__(self, limit):
self.limit = limit
self.current = 1 # Start from 1
def __iter__(self):
return self # Return the iterator object
def __next__(self):
if self.current > self.limit:
raise StopIteration # Stop when the limit is reached
value = self.current
self.current += 1
return value
# Creating an iterator object
numbers = MyNumbers(5)
iterator = iter(numbers)
# Printing numbers using the iterator
for num in iterator:
print(num)
Question 20:
Write a Python class SequenceIterator that acts as an iterator for any sequence type (like a
list, tuple, or string). The iterator should return elements one by one when iterated over.
Implement the __iter__() and __next__() methods to achieve this functionality.
class SequenceIterator:
"""An iterator for any of Python's sequence types."""
def __init__(self, sequence):
"""Create an iterator for the given sequence."""
self._seq = sequence # keep a reference to the underlying data
self._k = -1 # will increment to 0 on first call to next
def __next__(self):
"""Return the next element, or else raise StopIteration error."""
self._k += 1 # advance to next index
if self._k < len(self._seq):
return (self._seq[self._k]) # return the data element
else:
raise StopIteration() # there are no more elements
def __iter__(self):
"""By convention, an iterator must return itself as an iterator."""
return self
obj = SequenceIterator([1, 2, 3, 4, 5])
print(next(obj)) # 1
print(next(obj)) # 2
print(next(obj)) # 3
Question 21: Create an infinite iterator for odd numbers.
Write a Python class OddNumbers that generates an infinite sequence of odd numbers.
class OddNumbers:
def __init__(self):
self.num = 1
def __iter__(self):
return self
def __next__(self):
odd = self.num
self.num += 2 # Increment by 2 to get the next odd number
return odd
odd_iterator = OddNumbers()
for _ in range(5):
print(next(odd_iterator))
Question 22:
Write a Python generator function even_numbers(n) that yields even numbers up to n .
def even_numbers(n):
for i in range(0, n+1, 2): # Start from 0, step by 2
yield i
# Using the generator
for num in even_numbers(10):
print(num)