Python

🐍 Welcome to the Python Section! Whether you’re just starting out or looking to master advanced techniques, this section has you covered. It’s divided into three levels—Python Basics, Intermediate, and Advanced—each designed to build your skills progressively. From writing your first print() statement to crafting powerful, reusable code with object-oriented design and advanced functions, you’ll gain the tools and knowledge to tackle real-world programming tasks confidently.

Installation

Please refer to the Data Science Setup to make sure you are up and running!

Summary Table

Summary table of the Python section.

Basics

Concept Example Description
int 10 Integer
float 3.14 Floating point number
bool True, False Boolean value
str "hello" String
None None Null or no value
Assignment x = 10 Assigns value to a variable
Naming user_name = "Bob" Follows naming rules
Reassignment x = x + 1 Updates variable value
Multiple Assignment a, b = 1, 2 Assign multiple variables at once
Dynamic Assignment x = 5 → x = "hello" Variable type can change during execution
list [1, 2, 3] Mutable sequence
tuple (1, 2) Immutable sequence
set {1, 2, 3} Unordered unique elements
dict {'key': 'value'} Key-value mapping

Intermediate

Concept Example Description
Zero-based index data[0] Access the first element or character
Negative index data[-1] Access the last element or character
Nested indexing data[0][1] Access an element or character within a nested structure
String indexing "Text"[0] Access a character in a string
Slice range data[2:10] Elements or characters from index 2 up to (not including) 10
Slice from start data[:3] First 3 elements or characters
Slice to end data[4:] Elements or characters from index 4 to the end
Full slice data[:] Copy all elements or characters
Reversing data[::-1] Reverse the list or string
if if condition: Run block only if condition is True
else else: Run if all previous conditions are False
elif elif condition: Additional check after if
Logical Operators and, or, not Combine or negate multiple conditions
Nested Conditional Statements if ... if ... Place one conditional inside another
Truthy/Falsy if [], if "text" Empty values are False, non-empty are True
for Loops for item in sequence: Iterate over elements in a sequence
List Comprehension [x for x in sequence] Create a list using a loop in one line
Dictionary Comprehension {k: v for k, v in pairs} Create a dictionary using a loop in one line
while Loops while condition: Loop while a condition is True
break if condition: break Exit the loop immediately
continue if condition: continue Skip the current loop iteration
enumerate() for i, val in enumerate(seq): Loop with index and item
zip() for a, b in zip(list1, list2): Loop over multiple sequences in parallel
Infinite Loop while True: Runs forever unless externally stopped

Advanced

Concept Example Description
Basic function def my_function(): Define a reusable block of code
Parameters def my_function(param): Input values to the function
Return values return value Send a result back to the caller
Default values def my_function(param="default"): Provide fallback values for parameters
Keyword arguments my_function(arg2="value", arg1="val") Pass arguments by name
*args def my_function(*args): Handle multiple positional arguments
**kwargs def my_function(**kwargs): Handle multiple named keyword arguments
Multiple return values return val1, val2 Return several values as a tuple
Class definition class MyClass: Blueprint for creating objects
Object creation obj = MyClass() Instantiate an object from a class
__init__ method def __init__(self, ...) Set up initial object state
Attributes self.attribute Store data in the object
Methods def my_method(self): Function that operates on object data
self keyword self.value = value Refers to the current instance of the class
Class vs. instance attr MyClass.attr, self.attr Shared by all objects vs. unique per instance
Inheritance class SubClass(SuperClass): Derive one class from another
super() super().__init__(...) Call a method from the parent class
Object identity obj1 == obj2 Compare references vs. internal values
Basic import import module Load an entire module
Import specific parts from module import item1, item2 Bring in only selected functions, classes, etc.
Aliasing import module as alias Rename a module or function for convenience
Aliased import (partial) from module import item as alias Rename a specific item during import
Wildcard import from module import * Import everything from a module (not recommended)
Custom module import import mymodule Import your own Python files as modules
Conditional import if condition: import module Load a module only when needed
Import error import nonexistent Happens when module or item is not found