0% found this document useful (0 votes)
66 views4 pages

Python Programming Exercises Guide

The document contains a series of Python programming exercises covering basic I/O, arithmetic, conditional logic, loops, strings, functions, searching and sorting algorithms, recursion, object-oriented programming, and abstract data structures. Each exercise includes a problem statement followed by a sample solution in Python code. The exercises are designed to test various programming concepts and skills.

Uploaded by

miglanidivya28
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
66 views4 pages

Python Programming Exercises Guide

The document contains a series of Python programming exercises covering basic I/O, arithmetic, conditional logic, loops, strings, functions, searching and sorting algorithms, recursion, object-oriented programming, and abstract data structures. Each exercise includes a problem statement followed by a sample solution in Python code. The exercises are designed to test various programming concepts and skills.

Uploaded by

miglanidivya28
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Python Programming Practice

Q1. Basic I/O and Arithmetic (2 marks)

Write a Python program that asks the user for two integers and prints their
sum.

Answer:

a = int(input("Enter first number: "))


b = int(input("Enter second number: "))
print("Sum =", a + b)

Q2. Conditional Logic (3 marks)

Write a Python program that asks for a number and prints whether it is
even or odd.

Answer:

n = int(input("Enter a number: "))


if n % 2 == 0:
print("Even")
else:
print("Odd")

Q3. Loops (4 marks)

Write a program that prints all numbers from 1 to 20 that are divisible by 3.

Answer:

for i in range(1, 21):


if i % 3 == 0:
print(i)

Q4. Strings (4 marks)


Write a function that takes a string and returns the string reversed.

Answer:

def reverse_string(s):
return s[::-1]

print(reverse_string("IBCS"))

Q5. Functions & Lists (6 marks)

Write a function that takes a list of numbers and returns the average.

Answer:

def average(lst):
return sum(lst) / len(lst)

print(average([10, 20, 30, 40]))

Q6. Searching Algorithm (HL style – 6 marks)

Implement a linear search function that returns the index of an item in a


list, or -1 if not found.

Answer:

def linear_search(lst, target):


for i in range(len(lst)):
if lst[i] == target:
return i
return -1

print(linear_search([5, 10, 15, 20], 15)) # Output: 2

Q7. Sorting Algorithm (HL style – 8 marks)

Implement bubble sort to sort a list in ascending order.


Answer:

def bubble_sort(lst):
n = len(lst)
for i in range(n):
for j in range(0, n-i-1):
if lst[j] > lst[j+1]:
lst[j], lst[j+1] = lst[j+1], lst[j]
return lst

print(bubble_sort([64, 25, 12, 22, 11]))


# Output: [11, 12, 22, 25, 64]

Q8. Recursion (HL style – 6 marks)

Write a recursive function to compute the factorial of a number.

Answer:

def factorial(n):
if n == 0 or n == 1:
return 1
else:
return n * factorial(n - 1)

print(factorial(5)) # Output: 120

Q9. OOP (Object-Oriented Programming – 8 marks)

Create a Student class with attributes name and grade. Add a method
display() to print the details.

Answer:

class Student:
def __init__(self, name, grade):
[Link] = name
[Link] = grade
def display(self):
print("Name:", [Link], "| Grade:", [Link])

s1 = Student("Alice", "11")
[Link]()
# Output: Name: Alice | Grade: 11

Q10. HL Abstract Data Structures (10 marks)

Implement a stack class in Python with push(), pop(), and peek() methods.

Answer:

class Stack:
def __init__(self):
[Link] = []

def push(self, item):


[Link](item)

def pop(self):
if not self.is_empty():
return [Link]()
return None

def peek(self):
if not self.is_empty():
return [Link][-1]
return None

def is_empty(self):
return len([Link]) == 0

# Example usage
s = Stack()
[Link](10)
[Link](20)
print([Link]()) # Output: 20
print([Link]()) # Output: 20

Common questions

Powered by AI

Python uses the modulus operator % to determine if a number is even or odd. If the remainder when the number is divided by 2 is zero, the number is even; otherwise, it is odd. This logic is implemented using an if-else statement .

A recursive function computes the factorial by multiplying the number by the factorial of the number minus one, until it reaches the base case of 0 or 1, where the factorial is defined as 1. This breakdown into smaller subproblems until reaching a base case exemplifies recursion, reducing complex problems into simpler solvable parts .

Python handles basic I/O operations using the input() function to take user input, which is then converted to an integer using int(). To add two integers, Python adds them using the + operator and prints the result using the print() function .

Python allows reversing a string using slicing with the syntax s[::-1]. This means the slice starts from the end (last character) to the beginning (first character), effectively reversing the order of characters in the string without using loops or additional data structures .

To compute the average of a list of numbers, Python sums up all elements using the sum() function and divides the result by the list's length using len(). This calculation is encapsulated in a function that returns the average. This approach ensures modularity and reusability .

Python implements a stack using a list to store elements. The push() method appends an item to the end of the list, while the pop() method removes and returns the last item, if the stack is not empty. The peek() method returns the last item without removing it, and is_empty() checks if the stack is empty. This LIFO structure is crucial for operations like undo mechanisms in software .

A loop can be used to iterate over a range of numbers, and within the loop, a conditional statement checks if the current number is divisible by the given integer using the modulus operator. If the result is zero, it indicates divisibility, and the number is printed. This approach efficiently finds all divisible numbers in the defined range .

A linear search algorithm iterates through a list from the first element to the last, comparing each element with the target. If the target is found, the algorithm returns its index. If the end of the list is reached without finding the target, it returns -1. This method is straightforward but inefficient for large lists due to its O(n) complexity .

Python's OOP features are used to define a class with a constructor (__init__) for initializing attributes such as name and grade. Methods like display() are used for specific actions, demonstrating encapsulation and the creation of objects (instances) of the class, allowing for modular and reusable code .

The bubble sort algorithm repeatedly steps through the list, comparing adjacent elements and swapping them if they are in the wrong order. This process of bubbling up the largest unsorted element continues until no more swaps are needed, indicating the list is sorted. The algorithm's complexity is O(n^2) due to its nested loops .

You might also like