Overview
title: Python Quick Review author: Juma Shafara date: "2024-01" date-modified: "2024-08-14" description: This crash course will teach you the basics and advanced concepts of Python Programming keywords: [python basics, variables, numbers, operators, containers, flow control, advanced, modules, file handling]

Introduction
Python is a great general-purpose programming language on its own, but with the help of a few popular libraries (numpy, scipy, matplotlib) it becomes a powerful environment for scientific computing.
Whether you're a total beginner or seasoned programmer, this lesson will serve as a Python Quick Crash Course to refresh your Python knowledge
In this tutorial, we will cover:
Basic Python: Basic data types (Containers, Lists, Dictionaries, Sets, Tuples), Functions, Classes
A Brief Note on Python Versions
We'll be using Python 3.10 for this iteration of the course. You can check your Python version at the command line by running python --version.
Basics of Python
Python is a high-level, dynamically typed multiparadigm programming language. Python code is often said to be almost like pseudocode, since it allows you to express very powerful ideas in very few lines of code while being very readable. As an example, here is an implementation of the classic quicksort algorithm in Python:
def quicksort(array):
if len(array) <= 1:
return array
pivot = array[len(array) // 2]
left = [number for number in array if number < pivot]
middle = [number for number in array if number == pivot]
right = [number for number in array if number > pivot]
return quicksort(left) + middle + quicksort(right)
quicksort([3,6,8,10,1,2,1])
Rules to consider
- Variable names should be meaningful eg "number" instead of "x"
- Variable names should contain only alpha-numberic characters, and maybe under_scores
- Variable names can only start with letters or an underscore
- Variable name cannot contain special characters
- Variables names are case sensitive
Examples of variables
For this course, we'll use snake case for quick variables
we'll use camel case for function variables
finally, we'll use pascal case for class variables
Basic data types
Numbers
Integers and floats work as you would expect from other languages:
Booleans
Python implements all of the usual operators for Boolean logic, but uses English words rather than symbols:
Now we let's look at the operations:
Strings
A string is a sequence of characters under some quotes. Eg.
String objects have a bunch of useful methods; for example:
string_ = "hello"
print(string_.capitalize()) # Capitalize a string
print(string_.upper()) # Convert a string to uppercase; prints "HELLO"
print(string_.rjust(7)) # Right-justify a string, padding with spaces
print(string_.center(7)) # Center a string, padding with spaces
print(string_.replace('l', '(ell)')) # Replace all instances of one substring with another
print(' world '.strip()) # Strip leading and trailing whitespace
You can find a list of all string methods in the documentation.
Containers
- Python containers (collections) are objects that we use to group other objects
- Python includes several built-in container types: lists, dictionaries, sets, and tuples.
Lists
A list is an ordered collection of python objects or elements. A list can contain objects of different data types
Research on:
- `del`
- `remove()`
As usual, you can find all the gory details about lists in the documentation.
Slicing
In addition to accessing list elements one at a time, Python provides concise syntax to access a range of values in a list; this is known as slicing:
print(list_of_numbers) # Prints "[0, 1, 2, 3, 4]"
print(list_of_numbers[2:4]) # Get a slice from index 2 to 4 (exclusive); prints "[2, 3]"
print(list_of_numbers[2:]) # Get a slice from index 2 to the end; prints "[2, 3, 4]"
print(list_of_numbers[:2]) # Get a slice from the start to index 2 (exclusive); prints "[0, 1]"
print(list_of_numbers[:]) # Get a slice of the whole list; prints ["0, 1, 2, 3, 4]"
print(list_of_numbers[:-1]) # Slice indices can be negative; prints ["0, 1, 2, 3]"
list_of_numbers[2:4] = [8, 9] # Assign a new sublist to a slice
print(list_of_numbers) # Prints "[0, 1, 8, 9, 4]"
Loops
A for loop is used to loop through (or iterate) over a sequence of objects (iterable objects). Iterable objects in python include strings, lists, sets etc
You can loop over the elements of a list like this:
If you want access to the index of each element within the body of a loop, use the built-in enumerate function:
List comprehensions:
You can make this code simpler using a list comprehension:
List comprehensions can also contain conditions:
Research: How to combine lists
Dictionaries
- A dictionary is an unordered and mutable collection of items
- A dictionary is created using curly brackets
- Each item in a dictionary contains a key/value pair
Research:
- How to remove an item using the `del` method
- How to iterate over objects in a dictionary
- Imitate list comprehension with dictionaries
You can find all you need to know about dictionaries in the documentation.
Sets
- A set is an unordered, immutable collection of distinct elements.
- A set is created using curly braces
- The objects are placed inside the brackets and are separated by commas
- As a simple example, consider the following:
Research:
- How to remove with `discard()`
- How to remove with `pop()`
- How to combine sets/li>
- How to get the difference between 2 sets
- What happens when we have repeated elements in a set
Loops: Iterating over a set has the same syntax as iterating over a list; however since sets are unordered, you cannot make assumptions about the order in which you visit the elements of the set:
Set comprehensions: Like lists and dictionaries, we can easily construct sets using set comprehensions:
Tuples
- A tuple is an (immutable) ordered list of values.
- A tuple is in many ways similar to a list; one of the most important differences is that tuples can be used as keys in dictionaries and as elements of sets, while lists cannot. Here is a trivial example:
Research:
- Creating a tuple
- Access items in a tuple
- Negative indexing tuples
- Using range of indexes
- Getting the length of items in a tuple
- Looping through a tuple
- Checking if an item exists in a tuple
- How to combine tuples
- Prove that tuples are immutable
Functions
A function is a group of statements that performs a particular task
Python functions are defined using the def keyword. For example:
def overWeightOrUnderweightOrNormal(weight_kg:float, height_m:float) -> str:
'''
Tells whether someone is overweight or underweight or normal
'''
height_m2 = pow(height_m, 2)
bmi = weight_kg / height_m2
rounded_bmi = round(bmi, 3)
if bmi > 24:
return 'Overweight'
elif bmi > 18:
return 'Normal'
else:
return 'Underweight'
overWeightOrUnderweightOrNormal(67, 1.7)
We will often use functions with optional keyword arguments, like this:
Classes
- In python, everything is an object
- We use classes to help us create new object
- The syntax for defining classes in Python is straightforward:
Research:
Inheritance: This allows to create classes that inherit the attributes and methods of another class