Pythonexam
Pythonexam
Pythonexam
1. What is the purpose of the break and continue statements in Python loops? Give an
example of each within a for loop. (10 points)
Break statement: It is used to exit the loop prematurely, before the loop condition is false.
Continue statement: It is used to skip the rest of the code inside the loop for the current iteration and
move to the next iteration.
2. Explain the difference between local and global variables in Python. Provide an example where a
global variable is modified within a function. (10 points)
Local variables: Defined inside a function and can only be accessed within that function.
Global variables: Defined outside any function and can be accessed throughout the program.
Example:
global_var = 10
def modify_global():
global global_var
global_var += 5
modify_global()
print(global_var) # Output: 15
Class variables are variables that are shared among all instances of a class.
They are defined outside any method in the class and are typically placed at the top of the class definition.
Class variables are shared by all instances of the class, and their value is the same for each instance.
They are often used to store data that is common to all instances of the class.
Here's an example of a Python class Counter that keeps track of the number of instances created using a
class variable:
5. Given a list, write a Python expression that returns a new list with only the last three elements of the
original list.
6. Using a while loop, implement a Python function find_prime that finds and returns the first prime
number larger than a given integer n.
7. Explain how you would remove duplicates from a list in Python. Provide a code example that creates a
list with duplicates and then removes them.
8. Write a Python function multiply_elements that multiplies all the elements in a list that are passed to it as
a parameter. The list can contain any number of elements.
Exam ticket 2
1. Describe the range() function in Python and its usage in for loops.
Answer:
The `range()` function in Python generates a sequence of numbers. It takes up to three
arguments: `start` (optional, default is 0), `stop` (the end value, not inclusive), and
`step` (optional, default is 1). It is often used in `for` loops to iterate over a specific
range of values. The `for` loop then iterates over each value in the generated
sequence, allowing for concise and efficient iteration through numerical ranges.
2. Describe the difference between for and while loops. Give an example
Answer:
In Python, both `for` and `while` loops are control flow structures used for repetitive
tasks, but they differ in their syntax and use cases.
For Loop:
- A `for` loop is used when you know the number of iterations in advance.
- It iterates over a sequence (such as a list, tuple, string, or range) and executes the code
block for each element in the sequence.
- The loop variable takes on the value of each element in the sequence during each iteration.
Here's an example of a `for` loop:
# Iterate over a list of numbers
numbers = [1, 2, 3, 4, 5]
for num in numbers:
print(num)
This will output:
1
2
3
4
5
While Loop:
- A `while` loop is used when you don't know the number of iterations in advance, and the
loop continues until a certain condition is met.
- It repeatedly executes a block of code as long as the specified condition is true.
print(sum_numbers)
```
```
15
```
In summary, use a `for` loop when you know the number of iterations, and use a `while`
loop when you need to iterate based on a condition that may change during the loop
execution.
3. Write a Python script that prints all the numbers from 1 to 10 using a for loop.
Answer:
# Using a for loop to print numbers from 1 to 10
for number in range(1, 11):
print(number)
4. Write a Python code that opens a file called data.txt, reads its contents line by line,
and prints each line with line numbers prefixed.
Answer:
try:
# Open the file named "data.txt" for reading
with open("data.txt", "r") as file:
# Read the contents of the file line by line
for line_number, line in enumerate(file, start=1):
# Print each line with line numbers prefixed
print(f"Line {line_number}: {line.strip()}")
except FileNotFoundError:
print("File 'data.txt' not found.")
except Exception as e:
print(f"An error occurred: {e}")```
In this code:
- The `with open("data.txt", "r") as file` statement is used to open the file "data.txt" in
read mode.
- The `enumerate(file, start=1)` function is used to iterate over the file object, providing
both the line number and the line content.
- The `line.strip()` is used to remove leading and trailing whitespaces (including newline
characters) from each line before printing.
- The `try` and `except` blocks are used to handle potential errors, such as the file not
being found or other exceptions during file handling.
Make sure to replace the file handling part with the specific operations you want to
perform on the file. Additionally, ensure that the file "data.txt" exists in the specified
location or adjust the file path accordingly.
5. Given a list of numbers, write a single line of Python code using a list comprehension
to create a new list containing only the even numbers from the original list.
Answer:
python
original_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
print(even_numbers)
```
In this example, `original_list` contains a list of numbers. The list comprehension `[num
for num in original_list if num % 2 == 0]` iterates through each number in
`original_list` and selects only the even numbers based on the condition `num % 2 ==
0`. The resulting list (`even_numbers`) will only contain the even numbers from the
original list.
6. Given a list of integers, write a Python function that efficiently finds the pair of
numbers with the smallest absolute difference and returns the pair. Explain the time
complexity of your solution?
Answer:
```
def smallest_difference_pair(numbers):
if len(numbers) < 2:
return None
numbers.sort()
return min((numbers[i], numbers[i + 1]) for i in range(len(numbers) - 1), key=lambda
pair: pair[1] - pair[0])
# Example usage:
numbers_list = [4, 2, 8, 1, 5, 7]
result = smallest_difference_pair(numbers_list)
print("Pair with smallest absolute difference:", result)
```
This version uses the `min` function with a generator expression to find the pair with the
smallest absolute difference in a more concise way. The `key` parameter is used with
a lambda function to specify the sorting criterion based on the absolute difference
between the pair elements.
Answer:
In Python, dictionary keys must be immutable because dictionaries use a hash table for
efficient key-value mapping. Immutable keys ensure a stable and predictable hash
value, which is crucial for dictionary operations.
Examples of valid keys: strings, integers, and tuples (if they contain only immutable
elements).
Examples of invalid keys: lists, dictionaries, and sets, as they are mutable and can't
provide stable hash values.
8. What is the difference between an iterator and a generator in Python? Provide a code
example of a generator function that produces Fibonacci series up to n terms.
Answer:
**Iterator:**
- Implements `__iter__` and `__next__` methods.
- Maintains state during iteration.
- Raises `StopIteration` when no more elements.
**Generator:**
- Defined with a function and uses `yield` keyword.
- Suspends and resumes state.
- More memory-efficient for large sequences.
```python
def fibonacci_generator(n):
a, b = 0, 1
count = 0
# Example usage:
n = 10
fibonacci_sequence = list(fibonacci_generator(n))
print(f"Fibonacci series up to {n} terms:", fibonacci_sequence)
```
Exam ticket 3
class Circle:
def __init__(self, radius):
self.__radius = radius
def get_radius(self):
return self.__radius
def calculate_area(self):
return 3.14 * self.__radius ** 2
# Example usage:
my_circle = Circle(radius=5)
print(f"Radius: {my_circle.get_radius()}")
my_circle.set_radius(7)
print(f"Area: {my_circle.calculate_area()}")
In this concise example, the Circle class encapsulates the __radius attribute and provides public methods
for accessing and modifying it.
2. Explain the difference between local and global variables in Python. Provide an example where a
global variable is modified within a function. (10 points)
In Python, local variables are defined within a function and have limited scope, while global variables are defined outside
functions and can be accessed throughout the program.
3. How do lists and tuples differ in terms of mutability? Write a Python function that takes a tuple
and returns a list with the same elements. (10 points)
Lists:
Mutable: Elements can be added, removed, or modified after the list is created.
Defined using square brackets [].
Tuples:
4. Write a Python function merge_lists that takes two lists as arguments and returns a new list
consisting of unique elements that are present in either of the two lists. Ensure that the returned list is
sorted. (10 points)
5. Illustrate with an example how to use a dictionary comprehension to invert a dictionary, swapping
keys and values. (15 points)
6. Define a Python class named Circle. It should have an instance variable radius and two methods:
area and perimeter, which calculate and return the circle's area and perimeter, respectively. (15
points)
7. Create a Python class Square that inherits from a class Rectangle. Implement the __init__ method
which takes the length of the square's side and sets both the width and length in the superclass.
(15 points)
In this example, the Square class inherits from the Rectangle class. The __init__ method of the Square
class calls the __init__ method of the superclass (Rectangle) using super(), and both the length and width
are set to the side_length. This allows the Square class to reuse the functionality of the Rectangle class.
8. Write a simple Python program using Tkinter that creates a window with a button labeled 'Click
Me'. When the button is clicked, display a message dialog that says "Button Clicked!".
(15 points)
This program imports the tkinter module, creates a main window (root), and adds a button
labeled "Click Me" to the window. The show_message function is called when the button is
clicked, and it displays a message dialog using messagebox.showinfo. Finally, the program
enters the Tkinter event loop with root.mainloop(). When you run this program and click
the button, it will show a message dialog with the text "Button Clicked!".
Exam ticket 4
1. Explain the while loop and give an example of its usage. (10 points)
The while loop in Python is used to repeatedly execute a block of code as long as a specified
condition is true.
Example: counter = 1
print(counter)
counter += 1
2. Explain the difference between a list and a tuple in Python. Provide an example of a situation where
a tuple is more appropriate than a list. (10 points)
The main difference between a list and a tuple is mutability. Lists are mutable (can be modified), defined
with square brackets [], while tuples are immutable (cannot be modified) and use parentheses ().
Example:
# List example
my_list = [1, 2, 3]
my_list[0] = 10 # Valid - Lists are mutable
# Tuple example
my_tuple = (1, 2, 3)
# The following line would result in an error:
# my_tuple[0] = 10 # Invalid - Tuples are immutable
In Python, nested loops refer to the situation where you have one loop inside another. This means that the
inner loop is executed multiple times for each iteration of the outer loop. The concept allows you to work
with two or more dimensions of data or perform repetitive tasks in a structured manner.
4. D
efine a
Python
function
named 'factorial' that takes an integer 'n' and returns the factorial of 'n'. Ensure your function includes
proper error handling for negative input values. (10 points)
This function uses recursion to calculate the factorial of 'n'. The base case handles the factorial of 0, which
is 1. The function also includes error handling to raise a ValueError if the input 'n' is negative. The test
code demonstrates using the function with a non-negative value and catches any potential errors due to
negative inpu
5. Given a list of numbers, write a Python function that returns a list containing only the even numbers
using a loop and conditional statements. (15 points)
In this example, the filter_even_numbers function iterates through each number in the input list. If a
number is even (divisible by 2), it is appended to the even_numbers list. The final result is a list containing
only the even numbers from the original list.
try:
# Code that may raise exceptions
num1 = int(input("Enter the first number: "))
num2 = int(input("Enter the second number: "))
Explanation:
ValueError:
Likely to occur when the user enters a non-integer value while trying to convert input to an integer using int().
For example, if the user enters "abc" instead of a number.
ZeroDivisionError:
Likely to occur when attempting to divide by zero (simulated here with the condition if num2 == 0).
Division by zero is a common arithmetic error and should be handled to prevent program crashes.
The else block is executed if no exceptions occur, and the finally block is always executed, regardless of whether an exception occurred or not.
The except Exception as e block is a catch-all for unexpected errors that may not be explicitly handled by the previous except blocks.
7. Choose a standard library in Python and explain its purpose. Write a piece of code that
demonstrates one of its functionalities. (15 points)
One of the standard libraries in Python is the datetime module, which provides classes for working with dates and times. The
datetime module allows you to manipulate dates and times, perform arithmetic with them, and format them for display.
Example code:
8. Define a Python class named Rectangle. It should have two instance variables, length and width.
Include a method named area that calculates and returns the rectangle's area. (15 points)