Python Refresher
Because we’ll be using Python throughout the course
Comments and Strings
# This is a comment
"This is a string"
'A' # This is also a string
# Python has no char type
"""This is a
multi-line string,
not a comment."""
Variables (and Objects)
x = 374 # int object
y = 1.5 # float object
z = "Hi" # str object
Data Types
Commonly used:
Data structures:
f-Strings
name = "Elizabeth"�print(f"Hello {name}!")�# Hello Elizabeth!��a = 5�b = 10�print(f"Five plus ten is {a + b} and not {2 * (a + b)}.")�# Five plus ten is 15 and not 30.��print(f"{math.pi:.5f}")�# 3.14159
Control Flow
if mood == "Happy":� print("You know it!")
while grade == 'A':� print("Go Dukes!")� # infinite loop, btw
votes = [1, 3, 2, 1, 2]�for vote in votes:� print(vote)
Indentation is required (part of the syntax)
Functions
def add(x, y):� print(f"x is {x} and y is {y}")� return x + y
add(5, 6) # prints "x is 5 and y is 6" and returns 11
# Another way to call functions is with keyword arguments.�# Keyword arguments can arrive in any order.�add(y=6, x=5)
Type Hints
# Identifiers can optionally be annotated with type information.�def add(x: int, y: int) -> int:� print(f"x is {x} and y is {y}")� return x + y
age: int = 20
status: str # You don't need to initialize to specify the type.�if age < 18:� status = "Minor"�else:� status = "Adult"
Scope
global_variable = 'I am available everywhere'
def some_function():� print(global_variable)� local_variable = "only available within this function"� print(local_variable)
# the following code will raise an error, because�# 'local_variable' exists only inside some_function�print(local_variable)
Modules Example: hw1.py
# A Python source file defines a module with the same name.�# Other modules can be imported using the import statement.
import csv # built-in module from standard library�import go_dukes # searches for the file go_dukes.py
# Modules typically consist of function definitions.
# Executed only when this module is the main program.
if __name__ == "__main__":� print("Testing Testing 1...2...3...")
Docstrings Google Python Style Guide
If the first line of a module or function is a string,�then the string is interpreted as documentation.
def select(pk):� """Execute an SQL statement that selects one row from your table.�� Args:� pk (int): The id of the row to select.�� Returns:� tuple: The row for the specified pk, or None if not found.� """
Standard Library
VS Code Quick Start Guide