Python Programming Final Exam Comprehensive Study Guide
Final Exam Structure and Grading
The final exam consists of four primary sections and a bonus section.
Section 1: Key Terms and Definitions
Format: multiple choice questions.
Weight: point per question, totaling points.
Objective: Identify the correct definition of a specific Python term.
Section 2: Code Evaluation
Format: multiple choice questions.
Weight: point per question, totaling points.
Objective: Mental evaluation of code to identify the correct output.
Section 3: Debugging
Format: multiple choice questions.
Weight: point per question, totaling points.
Objective: Correctly identify the specific type of error within a provided code snippet.
Section 4: Programming
Format: Choice of questions to be solved by typing code into a text box.
Selection: You are provided with options and must select to solve.
Weight: points per question, totaling points.
Bonus Section
Format: Choice of complex programming options.
Selection: You may solve only option. No points are awarded for attempting both.
Weight: points.
Point Summary
Total Exam Points:
Total Bonus Points:
Maximum Total Points Available:
Essential Key Terms and Definitions
Variable: A name that refers to a value stored in memory.
Data Type: The kind of value a variable holds, such as integers, floats, strings, and booleans.
Function: A block of code that performs a specific task and can be reused.
Iteration: The repeated execution of a block of code, typically using a loop.
Conditional Statement: Code that executes based on whether a condition is true or false.
List: An ordered collection of items that can be of different data types.
Dictionary: A collection of key-value pairs, where each key is unique.
Tuple: An ordered collection of items that is immutable, meaning it cannot be changed.
Set: An unordered collection of unique items.
String: A sequence of characters.
Module: A file containing Python code that can be imported and used in other programs.
Class: A blueprint for creating objects, defining their properties and behaviors.
Object: An instance of a class.
Exception Handling: Code that manages errors and exceptions to prevent program crashes (e.g., using
tryandexcept).Library: A collection of modules and functions that provide additional functionality.
Boolean: A data type with only two possible values:
TrueorFalse. It is frequently used in conditional statements.Index: The position of an item in an ordered collection, such as a list, string, or tuple. Indexing in Python starts at .
Slice: A method used to retrieve a subset of a sequence. The syntax for slicing is
sequence[start:stop:step].Comment: Text in the code preceded by the
#symbol. It is ignored by the interpreter and used for human-readable explanations.Import: A statement used to include external modules or libraries into a program.
Indentation: The whitespace at the beginning of lines that defines code blocks in Python.
Argument: A value provided to a function when it is called.
Return: A statement used within a function to send a result back to the caller.
Type Casting: The process of converting a value from one data type to another, such as converting a
strto anint.
Code Evaluation and Data Types
The
type()FunctionThis function is used to determine the data type of an object.
Example:
x = 10followed byprint(type(x))outputs<class 'int'>.Example:
y = "hello"followed byprint(type(y))outputs<class 'str'>.Example:
z = 10.5followed byprint(type(z))outputs<class 'float'>.
Type Compatibility and Errors
Combining an integer and a string using addition () results in a
TypeError: unsupported operand type(s) for +: 'int' and 'str'.Combining an integer and a float () results in a float. For instance,
type(b)whereb = 10 + 10.5is<class 'float'>.
The
print()FunctionThis function outputs data to the standard output device, usually the console.
It can take multiple arguments, which are converted to strings and separated by a space by default. It is essential for debugging and displaying results.
String Concatenation and Formatting
Simple Concatenation:
first_name = "John",last_name = "Doe",full_name = first_name + " " + last_nameoutputsJohn Doe.Concatenation with Numbers:
age = 25,message = "John is " + str(age) + " years old."outputsJohn is 25 years old.(Note the use ofstr()for type casting).f-strings:
name = "Alice",city = "Wonderland",greeting = f"{name} lives in {city}."outputsAlice lives in Wonderland.
Sequence Operations: Slicing and Indexing
Basic Slicing
text = "Hello, world!"slice_text = text[0:5]outputsHello.
Slicing with Step
text = "abcdef"slice_text = text[::2]outputsace.
Negative Indexing
text = "Hello, world!"slice_text = text[-6:-1]outputsworld.
String Reversal
text = "Python"reverse_text = text[::-1]outputsnohtyP.
Math Functions and Logic
Addition:
def add(a, b): return a + b.add(3, 5)returns .Subtraction:
def subtract(a, b): return a - b.subtract(10, 4)returns .Multiplication:
def multiply(a, b): return a * b.multiply(7, 6)returns .Division with Safety Check:
python def divide(a, b): if b != 0: return a / b else: return "Division by zero is not allowed"divide(20, 4)returns
Squaring:
def square(x): return x ** 2.square(5)returns .Square Root: Requires
import math.math.sqrt(16)returns .
Identifying Python Error Types for Debugging
1. Syntax Errors
Defined as code that violates the language rules. Detected before the program runs.
Example:
if x > 5(missing the colon:).Message:
SyntaxError: invalid syntax.
2. Indentation Errors
Occur when code blocks for functions, loops, or conditionals are not properly aligned.
Example:
python def greet(name): print("Hello, " + name) # Missing indentationMessage:
IndentationError: expected an indented block.
3. Index Errors
A runtime error occurring when attempting to access an invalid index.
Example:
x = [1, 2, 3]thenprint(x[3])(indices only go to ).Message:
IndexError: list index out of range.
4. Logical Errors
The program runs without crashing but produces the wrong result due to flawed logic.
Example: A function intended to add numbers
return a - bby mistake.
5. Type Errors
Occur when an operation is applied to an inappropriate data type.
Example:
print("hello" + 5).Message:
TypeError: can only concatenate str (not "int") to str.
6. Name Errors
Occur when accessing a variable or function that has not been defined.
Example:
print(x)whenxhas no value assigned.Message:
NameError: name 'x' is not defined.
9. Value Errors
Occur when a function receives an argument of the right type but with an inappropriate value.
Example:
int("hello").Message:
ValueError: invalid literal for int() with base 10: 'hello'.
10. ZeroDivision Errors
Occur when attempting to divide a number by zero.
Example:
x = 10 / 0.Message:
ZeroDivisionError: division by zero.
Programming Logic Scenarios
Scenario 1: Age Classification
Logic: Ask for age; if less than , print "Minor"; if less than , print "Adult"; else print "Senior".
Implementation:
python age = int(input("Enter your age: ")) if age < 18: print("Minor") elif age < 65: print("Adult") else: print("Senior")
Scenario 2: List Extremes
Logic: Find the largest and smallest numbers in a list.
Implementation:
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9],print("Minimum:", min(numbers)),print("Maximum:", max(numbers)).
Scenario 3: Vowel Counting
Logic: Count how many vowels are in a user-provided string.
Method A (Generator):
count = sum(1 for char in text if char in "aeiou").Method B (Loop):
python text = input("Enter a string: ") vowels = "aeiouAEIOU" count = 0 for char in text: if char in vowels: count = count + 1 print("Number of vowels:", count)
Scenario 4: Random Number Filtering
Logic: Generate random integers between and ; print those divisible by .
Method A (Comprehension):
python import random numbers = [random.randint(1, 100) for i in range(10)] print("Divisible by 3:", [n for n in numbers if n % 3 == 0])
Scenario 5: Multiplication Table
Logic: Prompt for a number ; print table up to .
While Loop Method:
python n = int(input("Enter a number: ")) i = 1 while i <= 10: print(n, "x", i, "=", n * i) i = i + 1
Scenario 6: Reversing a Word
Logic: Manually reverse a string using a loop.
Implementation:
python word = input("Enter a word: ") reversed_word = "" for letter in word: reversed_word = letter + reversed_word print("Reversed:", reversed_word)
Scenario 7: Prime Number Finder
Logic: Print all prime numbers less than user input .
Implementation:
python n = int(input("Enter a number: ")) for num in range(2, n): is_prime = True for i in range(2, num): if num % i == 0: is_prime = False break if is_prime: print(num)
Scenario 8: Integer Classification Loop
Logic: Iterate through a list and label numbers as positive, negative, or zero.
Implementation:
python numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] for n in numbers: if n > 0: print(n, "is positive") elif n < 0: print(n, "is negative") else: print(n, "is zero")