Python Programming Review Notes
Python is often praised for its clean and readable syntax, which makes it accessible for beginners. It does not
require explicit type declarations because it uses dynamic typing - meaning the type of a variable is inferred
based on the assigned value during runtime. This flexibility allows variables to be reassigned to different
types as the program executes.
Comments in Python are crucial for documenting code and improving readability. They do not affect program
speed or execution but serve as notes for yourself and other programmers to understand the logic behind the
code, explain complex sections, or temporarily disable parts during debugging.
Data types such as tuples and lists serve different purposes. Tuples are immutable sequences, meaning
once created, their contents cannot be changed, making them ideal when you want to protect data from
accidental modifications. Lists, on the other hand, are mutable and can be modified by adding or removing
elements.
When working with loops, the `while` loop runs based on a condition and is useful when the number of
iterations depends on dynamic factors, whereas the `for` loop iterates over fixed sequences or ranges. The
`break` and `continue` statements control loop execution flow: `break` exits the loop completely, while
`continue` skips the rest of the current iteration and moves to the next one.
In object-oriented programming, polymorphism allows different classes to implement the same method in
unique ways, letting you interact with objects through a common interface. This supports flexible and
extendable code design.
File handling requires careful error management using `try...except` blocks to handle issues like missing files
or permission errors gracefully without crashing the program.
Dictionaries in Python are collections that maintain insertion order and use keys to map to values. Keys must
be immutable types (like strings or tuples) because mutable types like lists cannot be dictionary keys.
Code Example 1: Basic Calculator
Python Programming Review Notes
class BasicCalculator:
def calculate(self, num1, num2, operation):
if operation == 'add':
return num1 + num2
elif operation == 'subtract':
return num1 - num2
elif operation == 'multiply':
return num1 * num2
elif operation == 'divide':
if num2 == 0:
return "Error: Cannot divide by zero."
else:
return num1 / num2
else:
return "Error: Invalid operation."
calc = BasicCalculator()
num1 = float(input("Enter the first number: "))
num2 = float(input("Enter the second number: "))
operation = input("Enter operation (add, subtract, multiply, divide): ").lower()
result = [Link](num1, num2, operation)
print("Result:", result)
This program takes two numbers and an operation as input, performs the calculation, and handles
divide-by-zero errors gracefully.
The `input()` function always returns user input as a string. To use numeric data, you need to convert it
explicitly (e.g., with `int()` or `float()`), or else the program may raise errors on invalid conversions.
Code Example 2: List Manager
class ListManager:
def __init__(self):
[Link] = []
def append_item(self, item):
Python Programming Review Notes
[Link](item)
return f"Appended {item}. Current list: {[Link]}"
def insert_item(self, index, item):
if index < 0 or index > len([Link]):
return "Error: Invalid index."
[Link](index, item)
return f"Inserted {item} at index {index}. Current list: {[Link]}"
def delete_item(self, item):
if item in [Link]:
[Link](item)
return f"Deleted {item}. Current list: {[Link]}"
else:
return f"Error: {item} not found in the list."
def display(self):
return f"Current list: {[Link]}"
manager = ListManager()
print(manager.append_item(5))
print(manager.append_item(10))
print(manager.insert_item(1, 7))
print(manager.delete_item(10))
print([Link]())
This class allows you to manage a list by adding, inserting, deleting, and displaying items, while also handling
errors such as invalid indices or missing items.
Python keywords are grouped by their roles: for example, control flow keywords (`if`, `else`, `elif`, `for`,
`while`, `break`, `continue`) direct the program's execution path, while operator keywords (`and`, `or`, `not`,
`in`, `is`) perform logical operations.
Python's `elif` statement enhances code readability and efficiency by preventing deeply nested conditionals,
allowing for clear and linear checking of multiple conditions.
Python Programming Review Notes
When dealing with strings, triple quotes (`'''` or `"""`) allow for multi-line strings, which is very helpful for writing
long texts, documentation, or formatting output across several lines.
Important Points to Remember:
- Variable names are case-sensitive, so `Name`, `name`, and `NAME` are different variables.
- The floor division operator `//` divides and returns the integer part, discarding the remainder.
- Python does not allow variable names to start with numbers or include special characters such as `@` or
`$`.
- The plus symbol `+` is overloaded: it can perform numeric addition or string concatenation depending on
operand types.
Keep practicing by writing your own small programs, and focus on understanding how Python handles data
types dynamically and how object-oriented principles like encapsulation and inheritance can organize your
code efficiently.