Python Programming Quiz Questions PDF
Document Details
Tags
Summary
This document contains a collection of quiz questions on various Python programming concepts. Topics range from syntax and control structures to object-oriented programming and plagiarism considerations.
Full Transcript
Subject: Python programming language fundamentals \* Learning objective: Syntax Difficulty: Easy Cognitive Level: Knowledge - Question: Which of the following is the correct way to define a variable in Python? a) `int x = 5` b) `x := 5` c) `x = 5` d) `let x = 5` - Answer: c) `x = 5` Subject: Python...
Subject: Python programming language fundamentals \* Learning objective: Syntax Difficulty: Easy Cognitive Level: Knowledge - Question: Which of the following is the correct way to define a variable in Python? a) `int x = 5` b) `x := 5` c) `x = 5` d) `let x = 5` - Answer: c) `x = 5` Subject: Python programming language fundamentals \* Learning objective: Control structures Difficulty: Medium Cognitive Level: Application - Question: Write a Python program that prints all even numbers from 1 to 20 using a `for` loop. - Answer: ::: {#cb1.sourceCode} ``` {.sourceCode.python} for i in range(1, 21): if i % 2 == 0: print(i) ``` ::: Subject: Python programming language fundamentals \* Learning objective: Object-oriented concepts Difficulty: Hard Cognitive Level: Synthesis - Question: Design a Python class named `Car` that has attributes for `make`, `model`, and `year`. Include a method to display the car's information. - Answer: ::: {#cb2.sourceCode} ``` {.sourceCode.python} class Car: def __init__(self, make, model, year): self.make = make self.model = model self.year = year def display_info(self): print(f"{self.year} {self.make} {self.model}") # Example usage my_car = Car("Toyota", "Corolla", 2020) my_car.display_info() ``` ::: Subject: Avoiding plagiarism in programming assignments \* Learning objective: Understanding plagiarism Difficulty: Medium Cognitive Level: Comprehension - Question: Explain why it is important to avoid plagiarism in programming assignments and list two strategies to ensure your work is original. - Answer: Avoiding plagiarism is important because it ensures academic integrity and demonstrates your own understanding of the material. Two strategies to ensure originality are: 1) Writing code from scratch and 2) Properly citing any code snippets or libraries used from external sources. Subject: Importance of coding conventions and readability \* Learning objective: Understanding coding conventions Difficulty: Easy Cognitive Level: Knowledge - Question: Which of the following is a common coding convention in Python? a) Using camelCase for variable names b) Using tabs for indentation c) Using snake\_case for variable names d) Using all uppercase letters for function names - Answer: c) Using snake\_case for variable names Subject: Sequence, selection, and iteration constructs in programming \* Learning objective: Understanding basic constructs Difficulty: Medium Cognitive Level: Application - Question: Write a Python program that asks the user for a number and prints "Positive" if the number is greater than zero, "Negative" if it is less than zero, and "Zero" if it is exactly zero. - Answer: ::: {#cb3.sourceCode} ``` {.sourceCode.python} number = int(input("Enter a number: ")) if number > 0: print("Positive") elif number < 0: print("Negative") else: print("Zero") ``` ::: Subject: Google Collab environment for coding \* Learning objective: Using cloud-based coding environments Difficulty: Easy Cognitive Level: Knowledge - Question: What is Google Colab and how can it be used for coding in Python? - Answer: Google Colab is a cloud-based coding environment that allows users to write and execute Python code in a web browser. It is particularly useful for data analysis, machine learning, and collaborating on coding projects. Subject: Difference between.ipynb and.py files \* Learning objective: Understand the difference between.ipynb and.py files Difficulty: Easy Cognitive Level: Knowledge - Question: What is the primary difference between a `.ipynb` file and a `.py` file? - Answer: A `.ipynb` file is a Jupyter Notebook file that can contain both code and rich text elements (paragraphs, equations, figures, links, etc.), while a `.py` file is a plain Python script that contains only Python code. Subject: Difference between.ipynb and.py files \* Learning objective: Understand the difference between.ipynb and.py files Difficulty: Medium Cognitive Level: Application - Question: Given a Jupyter Notebook file named `analysis.ipynb`, write the command you would use in the terminal to convert it to a Python script. - Answer: ::: {#cb4.sourceCode} ``` {.sourceCode.sh} jupyter nbconvert --to script analysis.ipynb ``` ::: Subject: Difference between.ipynb and.py files \* Learning objective: Understand the difference between.ipynb and.py files Difficulty: Medium Cognitive Level: Evaluation - Question: Evaluate the following statement: "Jupyter Notebooks are superior to Python scripts for all types of programming tasks." Do you agree or disagree? Provide reasons for your answer. - Answer: Disagree. Jupyter Notebooks are superior for tasks that involve data analysis, visualization, and interactive development because they allow for combining code, text, and visualizations in one document. However, Python scripts are more suitable for production code, automation, and larger projects because they are easier to manage with version control systems, are more modular, and can be executed directly by Python interpreters without the need for a Jupyter environment. Subject: Using Google Colab with.ipynb and.py files \* Learning objective: Use Google Colab to run.ipynb and.py files Difficulty: Medium Cognitive Level: Application - Question: Describe the steps to run a `.py` file in Google Colab. - Answer: To run a `.py` file in Google Colab, follow these steps: 1. Upload the `.py` file to your Colab environment by clicking on the "Files" tab and then the "Upload" button. 2. Use the `%run` magic command followed by the file name to execute the script. For example, `%run script.py`. Subject: Using Google Colab with.ipynb and.py files \* Learning objective: Use Google Colab to run.ipynb and.py files Difficulty: Medium Cognitive Level: Application - Question: Write the code to upload a file named `data.csv` from your local machine to Google Colab. - Answer: ::: {#cb5.sourceCode} ``` {.sourceCode.python} from google.colab import files uploaded = files.upload() ``` ::: - Answer: After running this code, you will be prompted to select the `data.csv` file from your local machine to upload it to the Colab environment. Subject: Using the `if __name__ == "__main__":` construct \* Learning objective: Understand and use the `if __name__ == "__main__":` construct Difficulty: Easy Cognitive Level: Knowledge - Question: What is the purpose of the `if __name__ == "__main__":` construct in a Python script? - Answer: The `if __name__ == "__main__":` construct is used to check whether a Python script is being run directly or being imported as a module. Code within this block will only execute if the script is run directly, not if it is imported. Subject: Using the `if __name__ == "__main__":` construct \* Learning objective: Understand and use the `if __name__ == "__main__":` construct Difficulty: Medium Cognitive Level: Comprehension - Question: Explain why the `if __name__ == "__main__":` construct is useful when writing reusable modules. - Answer: The `if __name__ == "__main__":` construct is useful for writing reusable modules because it allows the script to run code only when it is executed directly, not when it is imported. This is helpful for testing the module's functionality without executing the test code when the module is imported into other scripts. Subject: Using the `if __name__ == "__main__":` construct \* Learning objective: Understand and use the `if __name__ == "__main__":` construct Difficulty: Medium Cognitive Level: Evaluation - Question: Evaluate the following statement: "Using the `if __name__ == "__main__":` construct is essential for all Python scripts." Do you agree or disagree? Provide reasons for your answer. - Answer: Disagree. Using the `if __name__ == "__main__":` construct is not essential for all Python scripts. It is primarily useful for scripts that are intended to be both executable and importable as modules. For scripts that are only meant to be run directly or do not need to be imported, this construct is not necessary. Subject: Writing and testing Python functions \* Learning objective: Write and test Python functions Difficulty: Medium Cognitive Level: Application - Question: Write a Python function named `square` that takes a single argument `x` and returns its square. Also, write a test case to verify the function works correctly for the input `4`. - Answer: ::: {#cb6.sourceCode} ``` {.sourceCode.python} def square(x): return x * x # Test case assert square(4) == 16, "Test case failed" print("Test case passed") ``` ::: Subject: Writing and testing Python functions \* Learning objective: Write and test Python functions Difficulty: Hard Cognitive Level: Analysis - Question: Analyze the following function. Identify any issues and suggest improvements. ::: {#cb7.sourceCode} ``` {.sourceCode.python} def square(x): return x ** 2 # Test case assert square(3) == 9, "Test case failed" assert square(-3) == 9, "Test case failed" assert square(0) == 0, "Test case failed" print("All test cases passed") ``` ::: - Answer: The function `square(x)` is correct and returns the square of `x`. The test cases are also correct and cover positive, negative, and zero values. No issues are identified, and the function is properly tested. Subject: Running Python code from different files \* Learning objective: Run Python code from different files Difficulty: Easy Cognitive Level: Knowledge - Question: How do you run a Python script from another Python script? - Answer: You can run a Python script from another Python script by using the `import` statement to import the script as a module or by using the `exec` function to execute the script's content. Subject: Running Python code from different files \* Learning objective: Run Python code from different files Difficulty: Medium Cognitive Level: Comprehension - Question: Explain the difference between using `import` and `exec` to run code from another Python file. - Answer: Using `import` allows you to import and use specific functions, classes, or variables from another Python file as a module. This method is more structured and maintainable. Using `exec` executes the entire content of another Python file as a string, which is less structured and can lead to potential security risks and maintainability issues. Subject: Running Python code from different files \* Learning objective: Run Python code from different files Difficulty: Medium Cognitive Level: Evaluation - Question: Evaluate the following approach to running code from another file. Is it a good practice? Why or why not? ::: {#cb8.sourceCode} ``` {.sourceCode.python} # main.py exec(open("helper.py").read()) ``` ::: - Answer: This approach is not considered good practice because using `exec` to run code from another file can lead to security risks and maintainability issues. It executes all the code in the file, which might include unintended side effects. It is better to use the `import` statement to explicitly import and use only the necessary functions or classes from another file. Subject: Python imports and using modules \* Learning objective: Understand and use Python imports and modules Difficulty: Medium Cognitive Level: Application - Question: Write the code to import the `math` module and use its `sqrt` function to calculate the square root of 16. - Answer: ::: {#cb9.sourceCode} ``` {.sourceCode.python} import math result = math.sqrt(16) print(result) ``` ::: Subject: Python imports and using modules \* Learning objective: Understand and use Python imports and modules Difficulty: Hard Cognitive Level: Analysis - Question: Analyze the following code. What will be the output and why? ::: {#cb10.sourceCode} ``` {.sourceCode.python} import math from math import sqrt print(math.sqrt(25)) print(sqrt(25)) ``` ::: - Answer: The output will be: 5.0 5.0 Both `math.sqrt(25)` and `sqrt(25)` will return the square root of 25, which is `5.0`. The `math` module is imported entirely, so `math.sqrt` can be used with the module name, while `sqrt` is imported directly from the `math` module and can be used without the module name. Subject: Slicing lists in Python \* Learning objective: Understand and use slicing to manipulate lists in Python Difficulty: Easy Cognitive Level: Knowledge - Question: What is the output of the following code snippet? ::: {#cb12.sourceCode} ``` {.sourceCode.python} my_list = [1, 2, 3, 4, 5] print(my_list[1:4]) ``` ::: - Answer: The output will be `[2, 3, 4]`. Subject: Sorting and Searching Algorithms \* Learning objective: Bubble Sort Difficulty: Easy Cognitive Level: Comprehension - Question: Explain how the Bubble Sort algorithm works. - Answer: Bubble Sort repeatedly steps through the list, compares adjacent elements, and swaps them if they are in the wrong order. This process is repeated until the list is sorted. The algorithm gets its name because smaller elements "bubble" to the top of the list. ------------------------------------------------------------------------ Subject: Sorting and Searching Algorithms \* Learning objective: Bubble Sort Difficulty: Medium Cognitive Level: Application - Question: Write a Python function to implement the Bubble Sort algorithm. ::: {#cb13.sourceCode} ``` {.sourceCode.python} def bubble_sort(arr): n = len(arr) for i in range(n): for j in range(0, n-i-1): if arr[j] > arr[j+1]: arr[j], arr[j+1] = arr[j+1], arr[j] return arr ``` ::: - Answer: ::: {#cb14.sourceCode} ``` {.sourceCode.python} def bubble_sort(arr): n = len(arr) for i in range(n): for j in range(0, n-i-1): if arr[j] > arr[j+1]: arr[j], arr[j+1] = arr[j+1], arr[j] return arr ``` ::: ------------------------------------------------------------------------ Subject: Sorting and Searching Algorithms \* Learning objective: Linear Search Difficulty: Easy Cognitive Level: Knowledge - Question: What is the time complexity of the Linear Search algorithm in the worst case? - Answer: O(n) ------------------------------------------------------------------------ Subject: Sorting and Searching Algorithms \* Learning objective: Linear Search Difficulty: Medium Cognitive Level: Application - Question: Write a Python function to implement the Linear Search algorithm. ::: {#cb15.sourceCode} ``` {.sourceCode.python} def linear_search(arr, target): for i in range(len(arr)): if arr[i] == target: return i return -1 ``` ::: - Answer: ::: {#cb16.sourceCode} ``` {.sourceCode.python} def linear_search(arr, target): for i in range(len(arr)): if arr[i] == target: return i return -1 ``` ::: ------------------------------------------------------------------------ Subject: Sorting and Searching Algorithms \* Learning objective: Binary Search Difficulty: Medium Cognitive Level: Application - Question: Write a Python function to implement the Binary Search algorithm. ::: {#cb17.sourceCode} ``` {.sourceCode.python} def binary_search(arr, target): left, right = 0, len(arr) - 1 while left 5.0 5 The first print statement uses division (`/`), which returns a float, and the second print statement uses floor division (`//`), which returns an integer. ------------------------------------------------------------------------ Subject: Python Programming \* Learning objective: Expressions (change produced) Difficulty: Medium Cognitive Level: Application - Question: Write a Python expression that calculates the square root of a number `n` using the exponentiation operator. - Answer: `n ** 0.5` ------------------------------------------------------------------------ Subject: Python Programming \* Learning objective: Expressions (change produced) Difficulty: Easy Cognitive Level: Knowledge - Question: True or False: An expression can include calls to functions. - Answer: True ------------------------------------------------------------------------ Subject: Python Programming \* Learning objective: Literals and variables Difficulty: Easy Cognitive Level: Knowledge - Question: Define the difference between a literal and a variable in Python. - Answer: A literal is a fixed value written directly in the code, such as `42` or `"hello"`. A variable is a name that can hold a value, which can be changed during the execution of the program. ------------------------------------------------------------------------ Subject: Python Programming \* Learning objective: Literals and variables Difficulty: Medium Cognitive Level: Comprehension - Question: Identify the literals and variables in the following code: ::: {#cb80.sourceCode} ``` {.sourceCode.python} x = 10 y = 20 z = x + y print(z) ``` ::: - Answer: - Literals: `10`, `20` - Variables: `x`, `y`, `z` ------------------------------------------------------------------------ Subject: Python Programming \* Learning objective: Literals and variables Difficulty: Hard Cognitive Level: Analysis - Question: Analyze the following code and explain the role of literals and variables: ::: {#cb81.sourceCode} ``` {.sourceCode.python} a = 5 b = 3 c = a * b print(c) ``` ::: - Answer: In this code, `5` and `3` are literals, while `a`, `b`, and `c` are variables. The literals are assigned to the variables `a` and `b`, and the result of the expression `a * b` is assigned to the variable `c`. ------------------------------------------------------------------------ Subject: Python Programming \* Learning objective: Literals and variables Difficulty: Medium Cognitive Level: Application - Question: Write a Python function that uses both literals and variables to calculate and print the area of a rectangle. - Answer: `python def calculate_area(): width = 5 # Literal height = 10 # Literal week_3.txt --- Subject: IFS (if statements) * Learning objective: Understand and use if statements to control the flow of a program. Difficulty: Easy Cognitive Level: Knowledge - Question: What is the output of the following code snippet?`python x = 5 if x \ 3: print("x is greater than 3") \`\`\` - Answer: "x is greater than 3" Subject: IFS (if statements) \* Learning objective: Understand and use if statements to control the flow of a program. Difficulty: Medium Cognitive Level: Application - Question: Complete the following code snippet to print "Passed" if the score is greater than or equal to 50, otherwise print "Failed". ::: {#cb82.sourceCode} ``` {.sourceCode.python} score = int(input("Enter your score: ")) if ______________: print("Passed") else: print("Failed") ``` ::: - Answer: ::: {#cb83.sourceCode} ``` {.sourceCode.python} if score >= 50: ``` ::: Subject: IFS (if statements) \* Learning objective: Understand and use if statements to control the flow of a program. Difficulty: Medium Cognitive Level: Analysis - Question: Identify the error in the following code snippet and provide the corrected version. ::: {#cb84.sourceCode} ``` {.sourceCode.python} x = 10 if x > 10: print("x is greater than 10") else: print("x is not greater than 10") ``` ::: - Answer: Indentation is incorrect. Corrected version: ::: {#cb85.sourceCode} ``` {.sourceCode.python} x = 10 if x > 10: print("x is greater than 10") else: print("x is not greater than 10") ``` ::: Subject: Truthiness in Python \* Learning objective: Understand and evaluate the truthiness of different data types in Python. Difficulty: Medium Cognitive Level: Application - Question: Write a function `is_truthy` that takes any value and returns `True` if the value is truthy, otherwise returns `False`. - Answer: ::: {#cb86.sourceCode} ``` {.sourceCode.python} def is_truthy(value): return bool(value) ``` ::: Subject: Truthiness in Python \* Learning objective: Understand and evaluate the truthiness of different data types in Python. Difficulty: Hard Cognitive Level: Analysis - Question: Given the following code, what will be the output and why? ::: {#cb87.sourceCode} ``` {.sourceCode.python} def check_truthiness(val): if val: return "Truthy" else: return "Falsy" print(check_truthiness(0)) print(check_truthiness(1)) print(check_truthiness("")) print(check_truthiness("Hello")) ``` ::: - Answer: Falsy Truthy Falsy Truthy Explanation: `0` and `""` are considered "falsy" in Python, while `1` and `"Hello"` are considered "truthy". Subject: Comparison operations (\>, \=, \ b) ``` ::: - Answer: True Subject: Comparison operations (\>, \=, \ True False True Explanation: `a or b` is `True`, `not a` is `False`, and `a and not b` is `True`. Subject: Logical operators (and, or, not) \* Learning objective: Understand and use logical operators to combine conditions. Difficulty: Easy Cognitive Level: Knowledge - Question: What is the output of the following code snippet? ::: {#cb96.sourceCode} ``` {.sourceCode.python} print(True or False) ``` ::: - Answer: True Subject: Logical operators (and, or, not) \* Learning objective: Understand and use logical operators to combine conditions. Difficulty: Medium Cognitive Level: Application - Question: Complete the following code snippet to check if a number is either negative or greater than 100. ::: {#cb97.sourceCode} ``` {.sourceCode.python} number = int(input("Enter a number: ")) if ___________________: print("Number is either negative or greater than 100") else: print("Number is between 0 and 100") ``` ::: - Answer: ::: {#cb98.sourceCode} ``` {.sourceCode.python} if number < 0 or number 100: ``` ::: Subject: Logical operators (and, or, not) \* Learning objective: Understand and use logical operators to combine conditions. Difficulty: Hard Cognitive Level: Evaluation - Question: Write a function `complex_condition` that takes three boolean values `a`, `b`, and `c` and returns `True` if at least two of them are `True`, otherwise returns `False`. - Answer: ::: {#cb99.sourceCode} ``` {.sourceCode.python} def complex_condition(a, b, c): return (a and b) or (a and c) or (b and c) ``` ::: Subject: Handling user input and validating conditions \* Learning objective: Handle user input and validate conditions based on the input. Difficulty: Medium Cognitive Level: Application - Question: Write a function `is_valid_input` that takes a string input and returns `True` if the input is a digit and greater than 10, otherwise returns `False`. - Answer: ::: {#cb100.sourceCode} ``` {.sourceCode.python} def is_valid_input(user_input): return user_input.isdigit() and int(user_input) > 10 ``` ::: Subject: Handling user input and validating conditions \* Learning objective: Handle user input and validate conditions based on the input. Difficulty: Medium Cognitive Level: Analysis - Question: Given the following code, what will be the output if the user inputs "hello123" and why? ::: {#cb101.sourceCode} ``` {.sourceCode.python} user_input = input("Enter a string: ") if user_input.isalpha(): print("Alphabetic string") else: print("Not an alphabetic string") ``` ::: - Answer: "Not an alphabetic string" because "hello123" contains digits and is not purely alphabetic. Subject: Nested if statements and elif \* Learning objective: Understand and use nested if statements and elif to create complex conditional logic. Difficulty: Easy Cognitive Level: Knowledge - Question: What is the output of the following code snippet if `x` is 5? ::: {#cb102.sourceCode} ``` {.sourceCode.python} x = 5 if x > 3: if x < 10: print("x is between 3 and 10") ``` ::: - Answer: "x is between 3 and 10" Subject: Nested if statements and elif \* Learning objective: Understand and use nested if statements and elif to create complex conditional logic. Difficulty: Medium Cognitive Level: Application - Question: Complete the following code snippet to print "Teenager" if the age is between 13 and 19 inclusive, otherwise print "Not a teenager". ::: {#cb103.sourceCode} ``` {.sourceCode.python} age = int(input("Enter your age: ")) if ___________________: print("Teenager") else: print("Not a teenager") ``` ::: - Answer: ::: {#cb104.sourceCode} ``` {.sourceCode.python} if 13 0 1 2 ------------------------------------------------------------------------ Subject: While loops \* Learning objective: Debugging errors in while loops. Difficulty: Medium Cognitive Level: Analysis - Question: Identify and correct the error in the following while loop: ::: {#cb109.sourceCode} ``` {.sourceCode.python} i = 1 while i 0 1 2 ------------------------------------------------------------------------ Subject: For loops \* Learning objective: Debugging errors in for loops. Difficulty: Medium Cognitive Level: Analysis - Question: Identify and correct the error in the following for loop: ::: {#cb116.sourceCode} ``` {.sourceCode.python} for i in range(5) print(i) ``` ::: - Answer: ::: {#cb117.sourceCode} ``` {.sourceCode.python} for i in range(5): print(i) ``` ::: ------------------------------------------------------------------------ Subject: For loops \* Learning objective: Apply for loops to solve simple problems. Difficulty: Medium Cognitive Level: Application - Question: Write a for loop that calculates the factorial of 5. - Answer: ::: {#cb118.sourceCode} ``` {.sourceCode.python} factorial = 1 for i in range(1, 6): factorial *= i print(factorial) ``` ::: ------------------------------------------------------------------------ Subject: For loops \* Learning objective: Recognize the use cases for for loops. Difficulty: Medium Cognitive Level: Evaluation - Question: Explain why a for loop is more suitable than a while loop for iterating over the elements of a list. - Answer: A for loop is more suitable because it automatically handles the iteration over the elements of the list, reducing the risk of errors such as infinite loops or index out of range errors. ------------------------------------------------------------------------ Subject: When to use while vs. for loops \* Learning objective: Determine the appropriate loop type for a given task. Difficulty: Medium Cognitive Level: Application - Question: You need to iterate over a list of student names to print each name. Which loop would you use and why? - Answer: A for loop should be used because it is specifically designed for iterating over sequences like lists, making the code more concise and easier to read. ------------------------------------------------------------------------ Subject: When to use while vs. for loops \* Learning objective: Differentiate between the use cases for while and for loops. Difficulty: Medium Cognitive Level: Comprehension - Question: Explain the difference between while and for loops and provide an example scenario for each. - Answer: While loops are used when the number of iterations is not known beforehand and depends on a condition. For loops are used when the number of iterations is known or when iterating over a sequence. Example: Use a while loop for a user input validation loop and a for loop for iterating over a list of items. ------------------------------------------------------------------------ Subject: When to use while vs. for loops \* Learning objective: Compare and contrast while and for loops. Difficulty: Medium Cognitive Level: Analysis - Question: Analyze the following tasks and determine which loop type (while or for) would be more appropriate: 1. Printing numbers from 1 to 10. 2. Asking a user for input until they enter a valid response. - Answer: 1. For loop (since the number of iterations is known). 2. While loop (since the number of iterations is unknown and depends on user input). ------------------------------------------------------------------------ Subject: When to use while vs. for loops \* Learning objective: Select the correct loop based on the task requirements. Difficulty: Medium Cognitive Level: Evaluation - Question: Given the task of calculating the sum of numbers until the user enters a negative number, which loop would you use and why? - Answer: A while loop should be used because the number of iterations is not known beforehand and depends on the user's input. ------------------------------------------------------------------------ Subject: When to use while vs. for loops \* Learning objective: Apply knowledge of loop types to solve problems. Difficulty: Medium Cognitive Level: Application - Question: Write a loop (specify the type) to sum the even numbers from 1 to 10. - Answer: ::: {#cb119.sourceCode} ``` {.sourceCode.python} sum = 0 for i in range(1, 11): if i % 2 == 0: sum += i print(sum) ``` ::: ------------------------------------------------------------------------ Subject: Infinite loops \* Learning objective: Recognize infinite loops in code. Difficulty: Medium Cognitive Level: Evaluation - Question: Identify the issue in the following code that causes an infinite loop: ::: {#cb120.sourceCode} ``` {.sourceCode.python} i = 0 while i < 5: print(i) ``` ::: - Answer: The variable `i` is never incremented, so the condition `i < 5` will always be true, causing an infinite loop. ------------------------------------------------------------------------ Subject: Infinite loops \* Learning objective: Debug infinite loops. Difficulty: Medium Cognitive Level: Analysis - Question: Correct the following code to prevent it from running into an infinite loop: ::: {#cb121.sourceCode} ``` {.sourceCode.python} i = 0 while i < 3: print(i) ``` ::: - Answer: ::: {#cb122.sourceCode} ``` {.sourceCode.python} i = 0 while i < 3: print(i) i += 1 ``` ::: ------------------------------------------------------------------------ Subject: Infinite loops \* Learning objective: Understand the consequences of infinite loops. Difficulty: Medium Cognitive Level: Comprehension - Question: Explain what will happen if an infinite loop is run in a program. - Answer: If an infinite loop is run, the program will continue to execute the loop indefinitely, potentially causing the program to become unresponsive and consume excessive system resources. ------------------------------------------------------------------------ Subject: Infinite loops \* Learning objective: Identify and avoid infinite loops. Difficulty: Medium Cognitive Level: Evaluation - Question: What is a common mistake that leads to infinite loops in while loops? - Answer: A common mistake is failing to update the loop control variable within the loop, causing the loop condition to always evaluate to true. ------------------------------------------------------------------------ Subject: Infinite loops \* Learning objective: Recognize conditions that lead to infinite loops. Difficulty: Medium Cognitive Level: Analysis - Question: Analyze the following code and determine if it will result in an infinite loop. Explain your reasoning. ::: {#cb123.sourceCode} ``` {.sourceCode.python} x = 10 while x 0: print(x) x = x - 1 ``` ::: - Answer: This code will not result in an infinite loop because the loop control variable `x` is decremented in each iteration, and the loop will terminate when `x` becomes 0. ------------------------------------------------------------------------ Subject: Break and continue statements \* Learning objective: Understand the usage of break statements. Difficulty: Easy Cognitive Level: Knowledge - Question: What is the purpose of the break statement in loops? - Answer: The break statement is used to exit the loop prematurely when a certain condition is met. ------------------------------------------------------------------------ Subject: Break and continue statements \* Learning objective: Apply break statements in loops. Difficulty: Medium Cognitive Level: Application - Question: Write a for loop that prints numbers from 1 to 10 but stops if it encounters the number 5. - Answer: ::: {#cb124.sourceCode} ``` {.sourceCode.python} for i in range(1, 11): if i == 5: break print(i) ``` ::: ------------------------------------------------------------------------ Subject: Break and continue statements \* Learning objective: Understand the usage of continue statements. Difficulty: Easy Cognitive Level: Knowledge - Question: What is the purpose of the continue statement in loops? - Answer: The continue statement is used to skip the current iteration of the loop and proceed to the next iteration. ------------------------------------------------------------------------ Subject: Break and continue statements \* Learning objective: Apply continue statements in loops. Difficulty: Medium Cognitive Level: Application - Question: Write a for loop that prints numbers from 1 to 10 but skips the number 5. - Answer: ::: {#cb125.sourceCode} ``` {.sourceCode.python} for i in range(1, 11): if i == 5: continue print(i) ``` ::: ------------------------------------------------------------------------ Subject: Break and continue statements \* Learning objective: Use break and continue statements effectively. Difficulty: Medium Cognitive Level: Evaluation - Question: Explain the difference between break and continue statements with examples. - Answer: The break statement exits the loop entirely when a condition is met, whereas the continue statement skips the current iteration and proceeds to the next. Example: ::: {#cb126.sourceCode} ``` {.sourceCode.python} # break example for i in range(1, 6): if i == 3: break print(i) # Output: 1, 2 # continue example for i in range(1, 6): if i == 3: continue print(i) # Output: 1, 2, 4, 5 ``` ::: ------------------------------------------------------------------------ Subject: Iterating over lists \* Learning objective: Understand how to iterate over lists using loops. Difficulty: Easy Cognitive Level: Knowledge - Question: Write a for loop to iterate over the list `['apple', 'banana', 'cherry']` and print each element. - Answer: ::: {#cb127.sourceCode} ``` {.sourceCode.python} fruits = ['apple', 'banana', 'cherry'] for fruit in fruits: print(fruit) ``` ::: ------------------------------------------------------------------------ Subject: Iterating over lists \* Learning objective: Apply loops to iterate over lists. Difficulty: Medium Cognitive Level: Application - Question: Write a while loop to iterate over the list `[1, 2, 3, 4, 5]` and print each element. - Answer: ::: {#cb128.sourceCode} ``` {.sourceCode.python} numbers = [1, 2, 3, 4, 5] i = 0 while i < len(numbers): print(numbers[i]) i += 1 ``` ::: ------------------------------------------------------------------------ Subject: Iterating over lists \* Learning objective: Use list comprehensions as an alternative to loops. Difficulty: Medium Cognitive Level: Comprehension - Question: Rewrite the following for loop using a list comprehension: ::: {#cb129.sourceCode} ``` {.sourceCode.python} squares = [] for i in range(1, 6): squares.append(i**2) ``` ::: - Answer: ::: {#cb130.sourceCode} ``` {.sourceCode.python} squares = [i**2 for i in range(1, 6)] ``` ::: ------------------------------------------------------------------------ Subject: Iterating over lists \* Learning objective: Understand nested loops for iterating over lists of lists. Difficulty: Medium Cognitive Level: Knowledge - Question: Write a nested for loop to iterate over the list of lists `[[1, 2], [3, 4], [5, 6]]` and print each element. - Answer: ::: {#cb131.sourceCode} ``` {.sourceCode.python} list_of_lists = [[1, 2], [3, 4], [5, 6]] for sublist in list_of_lists: for item in sublist: print(item) ``` ::: ------------------------------------------------------------------------ Subject: Iterating over lists \* Learning objective: Use loops to manipulate list elements. Difficulty: Medium Cognitive Level: Application - Question: Write a for loop to iterate over the list `[2, 4, 6, 8, 10]` and create a new list containing each element multiplied by 2. - Answer: ::: {#cb132.sourceCode} ``` {.sourceCode.python} original_list = [2, 4, 6, 8, 10] new_list = [] for num in original_list: new_list.append(num * 2) print(new_list) # Output: [4, 8, 12, 16, 20] ``` ::: ------------------------------------------------------------------------ Subject: Control structures in loops \* Learning objective: Understand the use of if statements within loops. Difficulty: Easy Cognitive Level: Knowledge - Question: Write a for loop to print numbers from 1 to 10 but only if the number is even. - Answer: ::: {#cb133.sourceCode} ``` {.sourceCode.python} for i in range(1, 11): if i % 2 == 0: print(i) ``` ::: ------------------------------------------------------------------------ Subject: Control structures in loops \* Learning objective: Apply if-else statements within loops. Difficulty: Medium Cognitive Level: Application - Question: Write a while loop that prints "Even" if a number is even and "Odd" if a number is odd for numbers from 1 to 5. - Answer: ::: {#cb134.sourceCode} ``` {.sourceCode.python} i = 1 while i Hello, World! Hello, Alice! ------------------------------------------------------------------------ Subject: Objects in Python \* Learning objective: Understanding the basic concept of objects in Python Difficulty: Easy Cognitive Level: Knowledge - Question: In Python, everything is an object. True or False? - Answer: True ------------------------------------------------------------------------ Subject: Objects in Python \* Learning objective: Understanding how to create and use objects Difficulty: Medium Cognitive Level: Application - Question: Given the class definition below, create an instance of the `Dog` class with the name "Buddy" and age 3. ::: {#cb150.sourceCode} ``` {.sourceCode.python} class Dog: def __init__(self, name, age): self.name = name self.age = age ``` ::: - Answer: ::: {#cb151.sourceCode} ``` {.sourceCode.python} buddy = Dog("Buddy", 3) ``` ::: ------------------------------------------------------------------------ Subject: Objects in Python \* Learning objective: Understanding object attributes Difficulty: Medium Cognitive Level: Comprehension - Question: What will be the output of the following code? ::: {#cb152.sourceCode} ``` {.sourceCode.python} class Car: def __init__(self, make, model): self.make = make self.model = model my_car = Car("Toyota", "Corolla") print(my_car.make) print(my_car.model) ``` ::: - Answer: Toyota Corolla ------------------------------------------------------------------------ Subject: Objects in Python \* Learning objective: Understanding methods in objects Difficulty: Medium Cognitive Level: Application - Question: Complete the method definition so that the `Dog` class can bark. ::: {#cb154.sourceCode} ``` {.sourceCode.python} class Dog: def __init__(self, name): self.name = name # Complete the method def bark(self): pass my_dog = Dog("Rex") my_dog.bark() ``` ::: - Answer: ::: {#cb155.sourceCode} ``` {.sourceCode.python} class Dog: def __init__(self, name): self.name = name def bark(self): print("Woof!") my_dog = Dog("Rex") my_dog.bark() ``` ::: ------------------------------------------------------------------------ Subject: Objects in Python \* Learning objective: Understanding object-oriented principles Difficulty: Hard Cognitive Level: Synthesis - Question: Define a `Person` class that includes attributes for name and age, and a method that prints a greeting using the person's name. - Answer: ::: {#cb156.sourceCode} ``` {.sourceCode.python} class Person: def __init__(self, name, age): self.name = name self.age = age def greet(self): print(f"Hello, my name is {self.name} and I am {self.age} years old.") ``` ::: ------------------------------------------------------------------------ Subject: Mutability in Python \* Learning objective: Understanding mutable and immutable types Difficulty: Easy Cognitive Level: Knowledge - Question: Which of the following types are immutable in Python? (Select all that apply) - A) List - B) Tuple - C) Dictionary - D) String - Answer: B) Tuple, D) String ------------------------------------------------------------------------ Subject: Mutability in Python \* Learning objective: Understanding the concept of mutability Difficulty: Medium Cognitive Level: Comprehension - Question: Explain why the following code will raise an error: ::: {#cb157.sourceCode} ``` {.sourceCode.python} my_tuple = (1, 2, 3) my_tuple = 4 ``` ::: - Answer: Tuples are immutable, meaning their elements cannot be changed once they are created. Attempting to assign a new value to an element of a tuple will raise a `TypeError`. ------------------------------------------------------------------------ Subject: Mutability in Python \* Learning objective: Understanding mutable types Difficulty: Medium Cognitive Level: Application - Question: Given the following list, write a function that appends the number 4 to the list. ::: {#cb158.sourceCode} ``` {.sourceCode.python} my_list = [1, 2, 3] def append_four(lst): # Complete the function ``` ::: - Answer: ::: {#cb159.sourceCode} ``` {.sourceCode.python} def append_four(lst): lst.append(4) my_list = [1, 2, 3] append_four(my_list) print(my_list) # Output: [1, 2, 3, 4] ``` ::: ------------------------------------------------------------------------ Subject: Mutability in Python \* Learning objective: Understanding how mutability affects function arguments Difficulty: Hard Cognitive Level: Analysis - Question: Explain the difference in the output of the following two functions: ::: {#cb160.sourceCode} ``` {.sourceCode.python} def modify_list(lst): lst.append(4) def reassign_list(lst): lst = my_list = [1, 2, 3] modify_list(my_list) print(my_list) # Output? my_list = [1, 2, 3] reassign_list(my_list) print(my_list) # Output? ``` ::: - Answer: The output will be: [1, 2, 3, 4] [1, 2, 3] `modify_list` modifies the original list by appending 4, while `reassign_list` creates a new list inside the function scope and does not affect the original list. ------------------------------------------------------------------------ Subject: Mutability in Python \* Learning objective: Understanding how to use mutable and immutable types effectively Difficulty: Medium Cognitive Level: Application - Question: Given the following dictionary, write a function that updates the value associated with the key "age" to 30. ::: {#cb162.sourceCode} ``` {.sourceCode.python} person = {"name": "Alice", "age": 25} def update_age(d): # Complete the function ``` ::: - Answer: ::: {#cb163.sourceCode} ``` {.sourceCode.python} def update_age(d): d["age"] = 30 person = {"name": "Alice", "age": 25} update_age(person) print(person) # Output: {'name': 'Alice', 'age': 30} ``` ::: ------------------------------------------------------------------------ Subject: Declaring functions in Python \* Learning objective: Understanding the syntax of function declaration Difficulty: Easy Cognitive Level: Knowledge - Question: What is the correct syntax for declaring a function named `hello` that takes no parameters? - Answer: ::: {#cb164.sourceCode} ``` {.sourceCode.python} def hello(): pass ``` ::: ------------------------------------------------------------------------ Subject: Declaring functions in Python \* Learning objective: Understanding function headers Difficulty: Medium Cognitive Level: Comprehension - Question: What is the function header of a function named `multiply` that takes two parameters, `x` and `y`, and returns their product? - Answer: ::: {#cb165.sourceCode} ``` {.sourceCode.python} def multiply(x, y): return x * y ``` ::: ------------------------------------------------------------------------ Subject: Declaring functions in Python \* Learning objective: Understanding function signatures Difficulty: Medium Cognitive Level: Application - Question: Write a function named `subtract` that takes two parameters `a` and `b`, and returns the result of `a` minus `b`. - Answer: ::: {#cb166.sourceCode} ``` {.sourceCode.python} def subtract(a, b): return a - b ``` ::: ------------------------------------------------------------------------ Subject: Declaring functions in Python \* Learning objective: Understanding the use of docstrings Difficulty: Medium Cognitive Level: Comprehension - Question: Write a function named `divide` with a docstring that describes its purpose and parameters. - Answer: ::: {#cb167.sourceCode} ``` {.sourceCode.python} def divide(a, b): """ Divides the first parameter by the second parameter. Parameters: a (int or float): The numerator. b (int or float): The denominator. Returns: float: The result of the division. """ return a / b ``` ::: ------------------------------------------------------------------------ Subject: Declaring functions in Python \* Learning objective: Understanding function scope Difficulty: Hard Cognitive Level: Analysis - Question: What will be the output of the following code? ::: {#cb168.sourceCode} ``` {.sourceCode.python} x = 10 def change_x(): x = 5 change_x() print(x) ``` ::: - Answer: 10 ------------------------------------------------------------------------ Subject: Using functions in Python \* Learning objective: Understanding how to call functions Difficulty: Easy Cognitive Level: Knowledge - Question: How do you call a function named `greet` with no arguments? - Answer: `greet()` ------------------------------------------------------------------------ Subject: Using functions in Python \* Learning objective: Understanding function arguments Difficulty: Medium Cognitive Level: Comprehension - Question: What will be the output of the following code? ::: {#cb169.sourceCode} ``` {.sourceCode.python} def add(a, b): return a + b print(add(2, 3)) print(add(a=2, b=3)) print(add(b=3, a=2)) ``` ::: - Answer: 5 5 5 ------------------------------------------------------------------------ Subject: Using functions in Python \* Learning objective: Understanding variable scope within functions Difficulty: Medium Cognitive Level: Application - Question: What will be the output of the following code? ::: {#cb171.sourceCode} ``` {.sourceCode.python} x = 5 def set_x(): x = 10 set_x() print(x) ``` ::: - Answer: 5 ------------------------------------------------------------------------ Subject: Using functions in Python \* Learning objective: Understanding keyword arguments Difficulty: Hard Cognitive Level: Analysis - Question: Complete the function call to use keyword arguments. ::: {#cb172.sourceCode} ``` {.sourceCode.python} def describe_pet(animal_type, pet_name): print(f"I have a {animal_type} named {pet_name}.") # Complete the function call describe_pet() ``` ::: - Answer: ::: {#cb173.sourceCode} ``` {.sourceCode.python} describe_pet(animal_type="dog", pet_name="Buddy") ``` ::: ------------------------------------------------------------------------ Subject: Using functions in Python \* Learning objective: Understanding the use of functions in loops Difficulty: Medium Cognitive Level: Application - Question: Write a function named `print_numbers` that prints numbers from 1 to 5 using a loop. - Answer: ::: {#cb174.sourceCode} ``` {.sourceCode.python} def print_numbers(): for i in range(1, 6): print(i) print_numbers() ``` ::: ------------------------------------------------------------------------ Subject: Returning values from functions \* Learning objective: Understanding how to return values from functions Difficulty: Easy Cognitive Level: Knowledge - Question: What is the correct way to return a value from a function in Python? - Answer: Use the `return` statement. ------------------------------------------------------------------------ Subject: Returning values from functions \* Learning objective: Understanding multiple return values Difficulty: Medium Cognitive Level: Comprehension - Question: Write a function named `swap` that takes two arguments and returns them in reverse order. - Answer: ::: {#cb175.sourceCode} ``` {.sourceCode.python} def swap(a, b): return b, a ``` ::: ------------------------------------------------------------------------ Subject: Returning values from functions \* Learning objective: Understanding the use of return values in expressions Difficulty: Medium Cognitive Level: Application - Question: What will be the output of the following code? ::: {#cb176.sourceCode} ``` {.sourceCode.python} def add(a, b): return a + b result = add(3, 4) * 2 print(result) ``` ::: - Answer: 14 ------------------------------------------------------------------------ Subject: Returning values from functions \* Learning objective: Understanding how to handle no return value Difficulty: Hard Cognitive Level: Analysis - Question: What will be the output of the following code? ::: {#cb177.sourceCode} ``` {.sourceCode.python} def do_nothing(): pass result = do_nothing() print(result) ``` ::: - Answer: None ------------------------------------------------------------------------ Subject: Returning values from functions \* Learning objective: Understanding the use of return values in conditional statements Difficulty: Medium Cognitive Level: Application - Question: Write a function named `is_even` that returns `True` if a number is even and `False` otherwise. - Answer: ::: {#cb178.sourceCode} ``` {.sourceCode.python} def is_even(n): return n % 2 == 0 ``` ::: ------------------------------------------------------------------------ Subject: Parameters and arguments in functions \* Learning objective: Understanding the use of parameters and arguments Difficulty: Easy Cognitive Level: Knowledge - Question: What is the difference between parameters and arguments in Python functions? - Answer: Parameters are variables listed inside the parentheses in the function definition, while arguments are the values passed to the function when it is called. ------------------------------------------------------------------------ Subject: Parameters and arguments in functions \* Learning objective: Understanding default parameter values Difficulty: Medium Cognitive Level: Comprehension - Question: What will be the output of the following code? ::: {#cb179.sourceCode} ``` {.sourceCode.python} def greet(name="Guest"): print(f"Hello, {name}!") greet() greet("Alice") ``` ::: - Answer: Hello, Guest! Hello, Alice! ------------------------------------------------------------------------ Subject: Parameters and arguments in functions \* Learning objective: Understanding variable-length arguments Difficulty: Medium Cognitive Level: Application - Question: Write a function named `sum_all` that takes any number of arguments and returns their sum. - Answer: ::: {#cb181.sourceCode} ``` {.sourceCode.python} def sum_all(*args): return sum(args) ``` ::: ------------------------------------------------------------------------ Subject: Parameters and arguments in functions \* Learning objective: Understanding keyword arguments Difficulty: Hard Cognitive Level: Analysis - Question: Identify and correct the error in the following code: ::: {#cb182.sourceCode} ``` {.sourceCode.python} def display_info(name, age=30, city): print(f"Name: {name}, Age: {age}, City: {city}") display_info("Alice", "New York") ``` ::: - Answer: The default parameter `age` should be placed after the non-default parameter `city`. ::: {#cb183.sourceCode} ``` {.sourceCode.python} def display_info(name, city, age=30): print(f"Name: {name}, Age: {age}, City: {city}") display_info("Alice", "New York") ``` ::: ------------------------------------------------------------------------ Subject: Parameters and arguments in functions \* Learning objective: Understanding keyword-only arguments Difficulty: Medium Cognitive Level: Comprehension - Question: Write a function named `print_person` that requires the keyword argument `age`. - Answer: ::: {#cb184.sourceCode} ``` {.sourceCode.python} def print_person(name, *, age): print(f"Name: {name}, Age: {age}") print_person("Alice", age=25) ``` ::: ------------------------------------------------------------------------ Subject: Creating classes in Python \* Learning objective: Understanding the syntax for class creation Difficulty: Easy Cognitive Level: Knowledge - Question: What is the correct syntax for creating a class named `Animal` in Python? - Answer: ::: {#cb185.sourceCode} ``` {.sourceCode.python} class Animal: pass ``` ::: ------------------------------------------------------------------------ Subject: Creating classes in Python \* Learning objective: Understanding class attributes Difficulty: Medium Cognitive Level: Comprehension - Question: What will be the output of the following code? ::: {#cb186.sourceCode} ``` {.sourceCode.python} class Dog: species = "Canis familiaris" print(Dog.species) ``` ::: - Answer: `Canis familiaris` ------------------------------------------------------------------------ Subject: Creating classes in Python \* Learning objective: Understanding instance attributes Difficulty: Medium Cognitive Level: Application - Question: Write a class named `Person` with instance attributes `name` and `age`. - Answer: ::: {#cb187.sourceCode} ``` {.sourceCode.python} class Person: def __init__(self, name, age): self.name = name self.age = age ``` ::: ------------------------------------------------------------------------ Subject: Creating classes in Python \* Learning objective: Understanding class methods Difficulty: Hard Cognitive Level: Analysis - Question: Write a class named `Counter` with a class method `increment` that increments a class attribute `count`. - Answer: ::: {#cb188.sourceCode} ``` {.sourceCode.python} class Counter: count = 0 @classmethod def increment(cls): cls.count += 1 Counter.increment() print(Counter.count) # Output: 1 ``` ::: ------------------------------------------------------------------------ Subject: Creating classes in Python \* Learning objective: Understanding inheritance Difficulty: Medium Cognitive Level: Comprehension - Question: Write a class named `Cat` that inherits from the `Animal` class and has an additional method named `meow`. - Answer: ::: {#cb189.sourceCode} ``` {.sourceCode.python} class Animal: def __init__(self, name): self.name = name class Cat(Animal): def meow(self): print("Meow!") my_cat = Cat("Whiskers") my_cat.meow() ``` ::: ------------------------------------------------------------------------ Subject: Using methods in Python classes \* Learning objective: Understanding instance methods Difficulty: Easy Cognitive Level: Knowledge - Question: What is the correct way to define an instance method in a class in Python? - Answer: An instance method is defined with the first parameter `self` inside a class. ------------------------------------------------------------------------ Subject: Using methods in Python classes \* Learning objective: Understanding how to call instance methods Difficulty: Medium Cognitive Level: Comprehension - Question: What will be the output of the following code? ::: {#cb190.sourceCode} ``` {.sourceCode.python} class Dog: def __init__(self, name): self.name = name def bark(self): return "Woof!" my_dog = Dog("Rex") print(my_dog.bark()) ``` ::: - Answer: `Woof!` ------------------------------------------------------------------------ Subject: Using methods in Python classes \* Learning objective: Understanding class methods Difficulty: Medium Cognitive Level: Application - Question: Write a class named `Circle` with a class method `pi_value` that returns the value of pi (3.14). - Answer: ::: {#cb191.sourceCode} ``` {.sourceCode.python} class Circle: @classmethod def pi_value(cls): return 3.14 ``` ::: ------------------------------------------------------------------------ Subject: Using methods in Python classes \* Learning objective: Understanding static methods Difficulty: Hard Cognitive Level: Analysis - Question: Write a class named `Math` with a static method `add` that takes two numbers and returns their sum. - Answer: ::: {#cb192.sourceCode} ``` {.sourceCode.python} class Math: @staticmethod def add(a, b): return a + b ``` ::: ------------------------------------------------------------------------ Subject: Using methods in Python classes \* Learning objective: Understanding method overloading Difficulty: Medium Cognitive Level: Comprehension - Question: Explain why Python does not support method overloading in the traditional sense. - Answer: Python does not support method overloading in the traditional sense because it allows for default arguments week\_7.txt --- Subject: Intersection function for sets \* Learning objective: Understand how to use the intersection function for sets Difficulty: Easy Cognitive Level: Knowledge - Question: What does the `intersection` method do when used on a set? - Answer: The `intersection` method returns a set containing only the elements that are present in all of the sets involved. ------------------------------------------------------------------------ Subject: Intersection function for sets \* Learning objective: Understand how to use the intersection function for sets Difficulty: Medium Cognitive Level: Application - Question: Given the sets `set1 = {1, 2, 3, 4}` and `set2 = {3, 4, 5, 6}`, write the Python code to find their intersection. - Answer: ::: {#cb193.sourceCode} ``` {.sourceCode.python} set1 = {1, 2, 3, 4} set2 = {3, 4, 5, 6} intersection_set = set1.intersection(set2) print(intersection_set) # Output: {3, 4} ``` ::: ------------------------------------------------------------------------ Subject: Intersection function for sets \* Learning objective: Understand how to use the intersection function for sets Difficulty: Medium Cognitive Level: Comprehension - Question: Explain why the intersection of the sets `{1, 2, 3}` and `{4, 5, 6}` is an empty set. - Answer: The intersection of the sets `{1, 2, 3}` and `{4, 5, 6}` is an empty set because there are no elements that are common to both sets. ------------------------------------------------------------------------ Subject: Intersection function for sets \* Learning objective: Understand how to use the intersection function for sets Difficulty: Hard Cognitive Level: Analysis - Question: Given three sets `A = {1, 2, 3}`, `B = {2, 3, 4}`, and `C = {3, 4, 5}`, write a Python function `find_common_elements` that returns the intersection of these three sets. - Answer: ::: {#cb194.sourceCode} ``` {.sourceCode.python} def find_common_elements(A, B, C): return A.intersection(B).intersection(C) A = {1, 2, 3} B = {2, 3, 4} C = {3, 4, 5} print(find_common_elements(A, B, C)) # Output: {3} ``` ::: ------------------------------------------------------------------------ Subject: Intersection function for sets \* Learning objective: Understand how to use the intersection function for sets Difficulty: Medium Cognitive Level: Synthesis - Question: Write a Python code snippet that takes a list of sets `sets_list` and returns their intersection. - Answer: ::: {#cb195.sourceCode} ``` {.sourceCode.python} def intersect_sets(sets_list): if not sets_list: return set() result = sets_list for s in sets_list[1:]: result = result.intersection(s) return result sets_list = [{1, 2, 3}, {2, 3, 4}, {3, 4, 5}] print(intersect_sets(sets_list)) # Output: {3} ``` ::: ------------------------------------------------------------------------ Subject: Union function for sets \* Learning objective: Understand how to use the union function for sets Difficulty: Easy Cognitive Level: Knowledge - Question: What does the `union` method do when used on a set? - Answer: The `union` method returns a set containing all unique elements from all of the sets involved. ------------------------------------------------------------------------ Subject: Union function for sets \* Learning objective: Understand how to use the union function for sets Difficulty: Medium Cognitive Level: Application - Question: Given the sets `set1 = {1, 2, 3}` and `set2 = {3, 4, 5}`, write the Python code to find their union. - Answer: ::: {#cb196.sourceCode} ``` {.sourceCode.python} set1 = {1, 2, 3} set2 = {3, 4, 5} union_set = set1.union(set2) print(union_set) # Output: {1, 2, 3, 4, 5} ``` ::: ------------------------------------------------------------------------ Subject: Union function for sets \* Learning objective: Understand how to use the union function for sets Difficulty: Medium Cognitive Level: Comprehension - Question: Explain why the union of the sets `{1, 2, 3}` and `{4, 5, 6}` contains all elements from both sets. - Answer: The union of the sets `{1, 2, 3}` and `{4, 5, 6}` contains all elements from both sets because the `union` method combines all unique elements from the sets without duplication. ------------------------------------------------------------------------ Subject: Union function for sets \* Learning objective: Understand how to use the union function for sets Difficulty: Hard Cognitive Level: Analysis - Question: Given three sets `A = {1, 2}`, `B = {2, 3}`, and `C = {3, 4}`, write a Python function `combine_all_elements` that returns the union of these three sets. - Answer: ::: {#cb197.sourceCode} ``` {.sourceCode.python} def combine_all_elements(A, B, C): return A.union(B).union(C) A = {1, 2} B = {2, 3} C = {3, 4} print(combine_all_elements(A, B, C)) # Output: {1, 2, 3, 4} ``` ::: ------------------------------------------------------------------------ Subject: Union function for sets \* Learning objective: Understand how to use the union function for sets Difficulty: Medium Cognitive Level: Synthesis - Question: Write a Python code snippet that takes a list of sets `sets_list` and returns their union. - Answer: ::: {#cb198.sourceCode} ``` {.sourceCode.python} def union_sets(sets_list): result = set() for s in sets_list: result = result.union(s) return result sets_list = [{1, 2, 3}, {3, 4, 5}, {5, 6, 7}] print(union_sets(sets_list)) # Output: {1, 2, 3, 4, 5, 6, 7} ``` ::: ------------------------------------------------------------------------ Subject: Checking if a set is a subset \* Learning objective: Understand how to check if a set is a subset of another set Difficulty: Easy Cognitive Level: Knowledge - Question: What does the `issubset` method do when used on a set? - Answer: The `issubset` method returns `True` if all elements of the set are contained in another set, otherwise it returns `False`. ------------------------------------------------------------------------ Subject: Checking if a set is a subset \* Learning objective: Understand how to check if a set is a subset of another set Difficulty: Medium Cognitive Level: Application - Question: Given the sets `set1 = {1, 2, 3}` and `set2 = {1, 2, 3, 4, 5}`, write the Python code to check if `set1` is a subset of `set2`. - Answer: ::: {#cb199.sourceCode} ``` {.sourceCode.python} set1 = {1, 2, 3} set2 = {1, 2, 3, 4, 5} print(set1.issubset(set2)) # Output: True ``` ::: ------------------------------------------------------------------------ Subject: Checking if a set is a subset \* Learning objective: Understand how to check if a set is a subset of another set Difficulty: Medium Cognitive Level: Comprehension - Question: Explain why the set `{1, 2, 3}` is a subset of the set `{1, 2, 3, 4, 5}`. - Answer: The set `{1, 2, 3}` is a subset of the set `{1, 2, 3, 4, 5}` because all elements of the first set are contained within the second set. ------------------------------------------------------------------------ Subject: Checking if a set is a subset \* Learning objective: Understand how to check if a set is a subset of another set Difficulty: Hard Cognitive Level: Analysis - Question: Given two sets `A` and `B`, write a Python function `is_subset` that returns `True` if `A` is a subset of `B`, otherwise `False`. - Answer: ::: {#cb200.sourceCode} ``` {.sourceCode.python} def is_subset(A, B): return A.issubset(B) A = {1, 2, 3} B = {1, 2, 3, 4, 5} print(is_subset(A, B)) # Output: True ``` ::: ------------------------------------------------------------------------ Subject: Checking if a set is a subset \* Learning objective: Understand how to check if a set is a subset of another set Difficulty: Medium Cognitive Level: Synthesis - Question: Write a Python code snippet that takes a list of sets `sets_list` and a set `main_set`, and checks if each set in the list is a subset of `main_set`. - Answer: ::: {#cb201.sourceCode} ``` {.sourceCode.python} def check_subsets(sets_list, main_set): return [s.issubset(main_set) for s in sets_list] sets_list = [{1, 2}, {2, 3}, {3, 4}] main_set = {1, 2, 3, 4, 5} print(check_subsets(sets_list, main_set)) # Output: [True, True, True] ``` ::: ------------------------------------------------------------------------ Subject: Creating a set from a string \* Learning objective: Understand how to create a set from a string Difficulty: Easy Cognitive Level: Knowledge - Question: What is the result of the expression `set('hello')`? - Answer: The result is `{'h', 'e', 'l', 'o'}` (Note: Sets are unordered, so the actual order may vary). ------------------------------------------------------------------------ Subject: Creating a set from a string \* Learning objective: Understand how to create a set from a string Difficulty: Medium Cognitive Level: Application - Question: Write the Python code to create a set from the string `'abracadabra'`. - Answer: ::: {#cb202.sourceCode} ``` {.sourceCode.python} string = 'abracadabra' string_set = set(string) print(string_set) # Output: {'a', 'b', 'r', 'c', 'd'} ``` ::: ------------------------------------------------------------------------ Subject: Creating a set from a string \* Learning objective: Understand how to create a set from a string Difficulty: Medium Cognitive Level: Comprehension - Question: Explain why the set created from the string `'banana'` contains only the characters `{'b', 'a', 'n'}`. - Answer: The set created from the string `'banana'` contains only the characters `{'b', 'a', 'n'}` because sets only store unique elements, and duplicates are removed. ------------------------------------------------------------------------ Subject: Creating a set from a string \* Learning objective: Understand how to create a set from a string Difficulty: Hard Cognitive Level: Analysis - Question: Given a list of strings `strings_list = ['apple', 'banana', 'cherry']`, write a Python function `unique_characters` that returns a set of all unique characters in these strings. - Answer: ::: {#cb203.sourceCode} ``` {.sourceCode.python} def unique_characters(strings_list): result = set() for string in strings_list: result.update(string) return result strings_list = ['apple', 'banana', 'cherry'] print(unique_characters(strings_list)) # Output: {'a', 'b', 'c', 'e', 'h', 'l', 'n', 'p', 'r', 'y'} ``` ::: ------------------------------------------------------------------------ Subject: Creating a set from a string \* Learning objective: Understand how to create a set from a string Difficulty: Medium Cognitive Level: Synthesis - Question: Write a Python code snippet that takes a string and returns a set of its characters, excluding any digits. - Answer: ::: {#cb204.sourceCode} ``` {.sourceCode.python} def create_set_excluding_digits(string): return {char for char in string if not char.isdigit()} string = 'h3ll0w0rld' print(create_set_excluding_digits(string)) # Output: {'h', 'l', 'w', 'r', 'd'} ``` ::: ------------------------------------------------------------------------ Subject: Adding and removing elements in sets \* Learning objective: Understand how to add and remove elements in sets Difficulty: Easy Cognitive Level: Knowledge - Question: What methods are used to add and remove elements from a set? - Answer: The methods used to add and remove elements from a set are `add()` and `remove()` respectively. ------------------------------------------------------------------------ Subject: Adding and removing elements in sets \* Learning objective: Understand how to add and remove elements in sets Difficulty: Medium Cognitive Level: Application - Question: Given the set `my_set = {1, 2, 3}`, write the Python code to add the element `4` and remove the element `2`. - Answer: ::: {#cb205.sourceCode} ``` {.sourceCode.python} my_set = {1, 2, 3} my_set.add(4) my_set.remove(2) print(my_set) # Output: {1, 3, 4} ``` ::: ------------------------------------------------------------------------ Subject: Adding and removing elements in sets \* Learning objective: Understand how to add and remove elements in sets Difficulty: Medium Cognitive Level: Comprehension - Question: Explain the difference between the `remove` and `discard` methods in sets. - Answer: The `remove` method raises a `KeyError` if the element to be removed is not present in the set, whereas the `discard` method does not raise an error if the element is not found. ------------------------------------------------------------------------ Subject: Adding and removing elements in sets \* Learning objective: Understand how to add and remove elements in sets Difficulty: Hard Cognitive Level: Analysis - Question: Given a set `A = {1, 2, 3}`, write a Python function `modify_set` that adds all elements from the list `elements_to_add` and removes all elements from the list `elements_to_remove`. - Answer: ::: {#cb206.sourceCode} ``` {.sourceCode.python} def modify_set(A, elements_to_add, elements_to_remove): for elem in elements_to_add: A.add(elem) for elem in elements_to_remove: A.discard(elem) return A A = {1, 2, 3} elements_to_add = [4, 5] elements_to_remove = [2, 3] print(modify_set(A, elements_to_add, elements_to_remove)) # Output: {1, 4, 5} ``` ::: ------------------------------------------------------------------------ Subject: Adding and removing elements in sets \* Learning objective: Understand how to add and remove elements in sets Difficulty: Medium Cognitive Level: Synthesis - Question: Write a Python code snippet that takes a set and a list of elements, adds the elements to the set, and then removes any elements from the set that are divisible by 3. - Answer: ::: {#cb207.sourceCode} ``` {.sourceCode.python} def add_and_remove_elements(my_set, elements): for elem in elements: my_set.add(elem) my_set = {elem for elem in my_set if elem % 3 != 0} return my_set my_set = {1, 2, 3} elements = [4, 5, 6] print(add_and_remove_elements(my_set, elements)) # Output: {1, 2, 4, 5} ``` ::: ------------------------------------------------------------------------ Subject: Using the pop function with sets \* Learning objective: Understand how to use the pop function with sets Difficulty: Easy Cognitive Level: Knowledge - Question: What does the `pop` method do when used on a set? - Answer: The `pop` method removes and returns an arbitrary element from the set. ------------------------------------------------------------------------ Subject: Using the pop function with sets \* Learning objective: Understand how to use the pop function with sets Difficulty: Medium Cognitive Level: Application - Question: Given the set `my_set = {1, 2, 3}`, write the Python code to use the `pop` method and print the modified set. - Answer: ::: {#cb208.sourceCode} ``` {.sourceCode.python} my_set = {1, 2, 3} popped_element = my_set.pop() print(my_set) # Output: The set with one element removed, e.g., {2, 3} print(popped_element) # Output: The element that was removed, e.g., 1 ``` ::: ------------------------------------------------------------------------ Subject: Using the pop function with sets \* Learning objective: Understand how to use the pop function with sets Difficulty: Medium Cognitive Level: Comprehension - Question: Explain why the `pop` method does not remove a specific element from a set. - Answer: The `pop` method does not remove a specific element from a set because sets are unordered collections, so the method removes and returns an arbitrary element. ------------------------------------------------------------------------ Subject: Using the pop function with sets \* Learning objective: Understand how to use the pop function with sets Difficulty: Hard Cognitive Level: Analysis - Question: Given a set `A = {1, 2, 3, 4, 5}`, write a Python function `pop_elements` that removes and returns all elements from the set one by one using the `pop` method. - Answer: ::: {#cb209.sourceCode} ``` {.sourceCode.python} def pop_elements(A): elements = [] while A: elements.append(A.pop()) return elements A = {1, 2, 3, 4, 5} print(pop_elements(A)) # Output: A list with all elements, e.g., [1, 2, 3, 4, 5] ``` ::: ------------------------------------------------------------------------ Subject: Using the pop function with sets \* Learning objective: Understand how to use the pop function with sets Difficulty: Medium Cognitive Level: Synthesis - Question: Write a Python code snippet that takes a set and uses the `pop` method to remove elements until the set is empty, printing each element as it is removed. - Answer: ::: {#cb210.sourceCode} ``` {.sourceCode.python} def pop_and_print_elements(my_set): while my_set: print(my_set.pop()) my_set = {1, 2, 3} pop_and_print_elements(my_set) # Output: # 1 (or any other element in the set) # 2 # 3 ``` ::: ------------------------------------------------------------------------ Subject: Creating and manipulating dictionaries \* Learning objective: Understand how to create and manipulate dictionaries Difficulty: Easy Cognitive Level: Knowledge - Question: How do you create an empty dictionary in Python? - Answer: An empty dictionary can be created using `{}` or `dict()`. ------------------------------------------------------------------------ Subject: Creating and manipulating dictionaries \* Learning objective: Understand how to create and manipulate dictionaries Difficulty: Medium Cognitive Level: Application - Question: Given the dictionary `my_dict = {'a': 1, 'b': 2}`, write the Python code to add the key-value pair `'c': 3` and update the value of key `'a'` to `10`. - Answer: ::: {#cb211.sourceCode} ``` {.sourceCode.python} my_dict = {'a': 1, 'b': 2} my_dict['c'] = 3 my_dict['a'] = 10 print(my_dict) # Output: {'a': 10, 'b': 2, 'c': 3} ``` ::: ------------------------------------------------------------------------ Subject: Creating and manipulating dictionaries \* Learning objective: Understand how to create and manipulate dictionaries Difficulty: Medium Cognitive Level: Com week\_8.txt --- Subject: Academic Integrity quiz \* Learning objective: Understand the importance of academic integrity and identify behaviors that constitute academic dishonesty. Difficulty: Easy Cognitive Level: Knowledge - Question: Which of the following actions is considered a violation of academic integrity? 1. Collaborating with classmates on a group project 2. Copying code from an online source without attribution 3. Discussing general concepts with a study group 4. Writing your own code based on provided specifications - Answer: 2. Copying code from an online source without attribution Subject: Academic Integrity quiz \* Learning objective: Recognize and practice proper citation and attribution in coding. Difficulty: Medium Cognitive Level: Application - Question: You found a useful piece of code on Stack Overflow that you want to use in your project. How should you properly include this code to adhere to academic integrity policies? - Answer: Include a comment in your code that attributes the source, including the author's name (if available) and a link to the original post. For example: `python # Code snippet from Stack Overflow by user123 (https://stackoverflow.com/questions/xxxxxx)` Subject: Academic Integrity quiz \* Learning objective: Understand the importance of academic integrity in collaborative work. Difficulty: Medium Cognitive Level: Comprehension - Question: Describe how you can ensure academic integrity while working on a group programming project. - Answer: Ensure that all group members contribute equally, properly attribute any external sources or code used, and avoid copying code from other groups or unauthorized sources. Document each member's contributions and maintain clear communication about the division of tasks. Subject: Asserts \* Learning objective: Use the `assert` statement to validate conditions in a program. Difficulty: Medium Cognitive Level: Application - Question: Write a Python code snippet using the `assert` statement to check if a variable `x` is greater than 0. - Answer: `python x = 5 assert x 0, "x should be greater than 0"` Subject: Asserts \* Learning objective: Apply `assert` statements to ensure code correctness. Difficulty: Hard Cognitive Level: Application - Question: Given the function `def divide(a, b): return a / b`, add an `assert` statement to ensure that the divisor `b` is not zero. - Answer: `python def divide(a, b): assert b != 0, "The divisor b should not be zero" return a / b` Subject: Exception handling \* Learning objective: Understand the concept of exception handling in Python. Difficulty: Easy Cognitive Level: Knowledge - Question: Which of the following is the correct way to handle an exception in Python? 1. `try:... except:...` 2. `catch:... try:...` 3. `try:... handle:...` 4. `except:... try:...` - Answer: 1. `try:... except:...` Subject: Exception handling \* Learning objective: Understand the flow of control in `try`, `except`, and `finally` blocks. Difficulty: Medium Cognitive Level: Comprehension - Question: Explain the purpose of the `finally` block in exception handling. - Answer: The `finally` block is used to execute code that should run regardless of whether an exception occurred or not. It is typically used for cleanup actions, such as closing files or releasing resources. Subject: Exception handling \* Learning objective: Implement exception handling in functions. Difficulty: Hard Cognitive Level: Application - Question: Modify the following function to handle both `ZeroDivisionError` and `ValueError` exceptions: `python def calculate(a, b): return a / b` - Answer: `python def calculate(a, b): try: return a / b except ZeroDivisionError: return "Cannot divide by zero!" except ValueError: return "Invalid input values!"` Subject: Creating and handling custom exceptions \* Learning objective: Raise custom exceptions in Python. Difficulty: Medium Cognitive Level: Application - Question: Raise a `NegativeValueError` exception if a given number is negative in the following function: `python def check_positive(number): if number < 0: # Raise custom exception here return number` - Answer: `python def check_positive(number): if number < 0: raise NegativeValueError("Number should be non-negative") return number` Subject: Creating and handling custom exceptions \* Learning objective: Understand the purpose of custom exceptions. Difficulty: Medium Cognitive Level: Comprehension - Question: Why might you create a custom exception rather than using a built-in exception? - Answer: Custom exceptions provide more specific error messages and allow for better error handling tailored to the specific needs of your application. They make your code more readable and maintainable by clearly indicating the type of error that occurred. Subject: Using the `assert` statement in Python \* Learning objective: Understand the use of `assert` in testing code conditions. Difficulty: Easy Cognitive Level: Knowledge - Question: What exception does the `assert` statement raise when the condition is False? 1. `ValueError` 2. `TypeError` 3. `AssertionError` 4. `IndexError` - Answer: 3. `AssertionError` Subject: Using the `assert` statement in Python \* Learning objective: Understand the optional error message in `assert` statements. Difficulty: Medium Cognitive Level: Comprehension - Question: What is the purpose of the optional error message in an `assert` statement? - Answer: The optional error message provides additional context and information about the failure when the assertion fails. This can help with debugging by making it clear why the assertion failed. Subject: Using the `assert` statement in Python \* Learning objective: Debugging with `assert` statements. Difficulty: Hard Cognitive Level: Analysis - Question: Given the function `def is_even(n): return n % 2 == 0`, add an `assert` statement to check if the input is an integer. - Answer: `python def is_even(n): assert isinstance(n, int), "Input must be an integer" return n % 2 == 0` Subject: Handling `ZeroDivisionError` \* Learning objective: Handle `ZeroDivisionError` exceptions in code. Difficulty: Medium Cognitive Level: Application - Question: Modify the following code to handle a `ZeroDivisionError`: `python result = 10 / 0 print(result)` - Answer: `python try: result = 10 / 0 except ZeroDivisionError: print("Cannot divide by zero!")` Subject: Handling `ZeroDivisionError` \* Learning objective: Combine `try`, `except`, and `finally` blocks to handle exceptions. Difficulty: Hard Cognitive Level: Application - Question: Modify the following code to use `finally` to print "Operation complete" regardless of whether an exception occurs: `python result = 10 / 0 print(result)` - Answer: `python try: result = 10 / 0 except ZeroDivisionError: print("Cannot divide by zero!") finally: print("Operation complete")` Subject: Handling `KeyError` \* Learning objective: Understand the `KeyError` exception. Difficulty: Easy Cognitive Level: Knowledge - Question: What causes a `KeyError` exception in Python? 1. Accessing a list with an invalid index 2. Accessing a dictionary with a non-existent key 3. Dividing a number by zero 4. Passing an incorrect argument type to a function - Answer: 2. Accessing a dictionary with a non-existent key Subject: Handling `KeyError` \* Learning objective: Use exception handling to access dictionary keys safely. Difficulty: Medium Cognitive Level: Comprehension - Question: Explain why handling `KeyError` is important when working with dictionaries. - Answer: Handling `KeyError` is important to avoid program crashes when trying to access a non-existent key in a dictionary. By catching this exception, the program can provide a meaningful error message or take alternative actions, ensuring smoother execution and better user experience. Subject: Handling `KeyError` \* Learning objective: Debugging dictionary operations with exception handling. Difficulty: Hard Cognitive Level: Analysis - Question: Given the function `def get_value(d, key): return d[key]`, add exception handling to manage `KeyError` and return `None` if the key is not found. - Answer: `python def get_value(d, key): try: return d[key] except KeyError: print(f"Key '{key}' not found in the dictionary") return None` Subject: Collecting, processing, and managing data from various sources \* Learning objective: Collecting, processing, and managing data from various sources Difficulty: Medium Cognitive Level: Application - Question: Write a Python script to read data from a CSV file named `sales_data.csv` and print the first 5 rows of the dataset. - Answer: ::: {#cb212.sourceCode} ``` {.sourceCode.python} import pandas as pd # Read the CSV file data = pd.read_csv('sales_data.csv') # Print the first 5 rows print(data.head()) ``` ::: Subject: Performing data analysis to identify trends, patterns, and insights \* Learning objective: Performing data analysis to identify trends, patterns, and insights Difficulty: Hard Cognitive Level: Analysis - Question: Given a DataFrame `df` with columns `date` and `sales`, write a Python script to identify the month with the highest total sales. - Answer: ::: {#cb213.sourceCode} ``` {.sourceCode.python} import pandas as pd # Convert 'date' column to datetime df['date'] = pd.to_datetime(df['date']) # Extract month and year df['month_year'] = df['date'].dt.to_period('M') # Group by month and year and calculate total sales monthly_sales = df.groupby('month_year')['sales'].sum() # Identify the month with the highest sales highest_sales_month = monthly_sales.idxmax() print(highest_sales_month) ``` ::: Subject: Combining data from multiple files into one dataset \* Learning objective: Combining data from multiple files into one dataset Difficulty: Medium Cognitive Level: Application - Question: Write a Python script to read data from multiple CSV files (`file1.csv`, `file2.csv`, `file3.csv`) and combine them into a single DataFrame. - Answer: ::: {#cb214.sourceCode} ``` {.sourceCode.python} import pandas as pd # List of file names file_list = ['file1.csv', 'file2.csv', 'file3.csv'] # Read and concatenate all files combined_df = pd.concat([pd.read_csv(file) for file in file_list], ignore_index=True) print(combined_df) ``` ::: Subject: Extracting specific parts of a string (e.g., cities and states from addresses) \* Learning objective: Extracting specific parts of a string (e.g., cities and states from addresses) Difficulty: Medium Cognitive Level: Application - Question: Write a Python function to extract the city and state from an address column in a DataFrame `df` and create two new columns `city` and `state`. - Answer: ::: {#cb215.sourceCode} ``` {.sourceCode.python} def extract_city_state(df): df[['city', 'state']] = df['address'].str.extract(r'(?P