Python Examples
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:
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.
OR:
num = 1
while num <= 5:
print(num)
num += 1
Question 5:
Write a for loop that prints even numbers from 2 to 10.
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"] .
OR:
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
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
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
def is_palindrome(text):
return text == text[::-1]
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))
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
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}")
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}"
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
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
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