Intro to Python
Python is an interpreted, object-orientated programming language.
Python builds server-side applications
To run a python file, in the command line, type:
- python filename.py
To use the python shell, type python into the terminal and enter.
You can try out code here before adding it into your application
You can exit the python shell using exit()
To install pytest libraries into your file,
simply enter pipenv install
Then type pipenv shell to enter the virtual environment
Type pytest into the command line to see all tests failing
- use pytest -x to see the failing tests 1 at a time
Common Data Types
Strings: Defined by single or double quotes. No backticks
To use string interpolation, use the f-string
dog_name = "Lucy" print(f"Say hell to {dog_name}")Use dir("hello") to see all methods you can use on the python object
Numbers: There are 2 types: Integers and floats
Integers are whole numbers like 3
Floats are decimal numbers like 3.45
You can convert some data types to numbers with int() and float()
int("1") #= 1 int(1.1) #= 1 float("1.1") #= 1.1Sequence Types
Lists: Use brackets to create a list. Similar to a javascript array
You can create a list with the list() syntax, which creates an empty list
To access a specific element in the list, you use the index
list_abc = ['a', 'b', 'c'] list_abc[0] #= 'a' Different functions to use on lists len([1, 3, 400]) #= 3 sorted([5, 200, 3, 100]) #= [3, 5, 100, 200] list_123 = [1, 2, 3] list_123.pop() - removes the last number from the list and returns it #= 3 list_123.remove(1) - removes the specific element from the list print(list_123) [2]Tuples: Nearly identical to lists but with 2 key differences
Tuples are created with open and close parentheses instead of square brackets
Tuples are immutable. That means once the tuple is created, the tuple itself cannot be changed.
- Python functions that work on lists to create new data will still work on tuples but not ones that mutate the tuple such as pop() and .insert()
Sets and Dicts
Sets: unindexed, unordered, and unchangeable
Unchangeable doesn't mean immutable. A set can still be changed via methods such as pop() or remove() but you can't change individual elements in the set.
It is initiated with curly brackets {} or with the set() constructor.
- The set() constructor takes a list or tuple as its argument.
Dictionaries: Python's equivalent of javascript objects
They are composed of key/value pairs
You can create a dictionary using key/value pairs enclosed in curly brackets
- Keys must be in string format
To access the data in dicts, you can use square brackets and pass in the key
- You can also use the .get() method to retrieve a key/value or check if the key exists
Reading Error Messages
Error messages have 3 parts
the location of the error
The type of the error
The description as to why
3 Common Error Types
Syntax errors: The result of incorrect syntax.
Logic errors: errors in the logic of your code such as infinite loops
Exceptions: Cover a wide variety of errors
they pop up when the interpreter knows what to do with a piece of code but is unable to complete the action
AssertionError
IndexError: when you try to access an element at an index past the end of a list
KeyError: when a key is references but does not exist
NameError: when a name is referenced before it has been defined.
TypeError: when an operation or function is applied to an object of the wrong type.
Functions in Python
def my_function(param):
print("Hello funcion")
return param + 1
use "def" to identify this code as a function
Use snake case for name
Parameters and arguements still defined in parenthesis
instead of curly brackets, use the colon after the parenthesis
INDENT ALL CODE PART OF THE FUNCTION
NEW CODE THAT IS NOT PART OF THE FUNCTION CAN START AT THE SAME INDENTATION AS DEF
You can place default params or arguments as well as follows:
def say_hi(name="friend"):
print(f"hello, {name}")
say_hi()
#= "hello friend"
say_hi("Bob")
#= "hello Bob"
Scope
variables declared outside of a function are available globally
functions declared inside a function cannot be accessed from outside the function
Control Flow Operators:
if/else statements
dog = "nice" if dog == "nice": owner == "PLay with dog" elif dog == "thirsty" owner == "fill dogs water" elif dog == "sleepy" owner == "put the dog to sleep" else dog == "cuddly" owner == "hug dog"Ternary Operators/Conditional Expressions
age = 1 is_baby = 'baby' if age < 2 else 'not a baby' value_if_true if condition else value_if_falseTry/Except Statements:
Exceptions are a type of error that we can intercept so that our Python application can continue to run.
Using try/except statements allows us to perform these interceptions
def divide(num1, num2): try: #Try this first quotient = num1/num2 print(quotient) except ZeroDivisionError: #If a ZeroDivisionError comes then this print("Error: num2 cannot equal 0") except TypeError: #If a type error comes then this print("Error: input must be of type int or float") finally: #This runs regardless print("This is fun")
Basic Loops in Python
While Loops:
i = 0 while (i<5): print("Loop") i += 1
For Loops:
For loops can proceed through any iterable object type
- List, tuple, set, dict, str, and range
A python FOR loop automatically proceeds to the next element in the iterable object.
- No need to increase the number or specify
for i in range(10): print(f"i is : {i}")
List Comprehensions
Used to iterate through lists and sets without writing out a whole for loop
list_1 = [1, 5, 7, 3, 6] list_2 = [num * 2 for num in list_1] #This will go through each number in list_1 and multiply them by 2
Intro to Data Structures
Sequences: simple data structure that is present in all programming languages in which data is stored in a specified order.
Elements can be accessed by their index
List and Tuples: Can Store any type of data
Range: only stores integers
String: Only store unicode characters
Sequences should be used whenever values are logically connected to one another and it is important to keep them in order
Common Sequence Operations where s = sequence
x in s
- returns true if x = atleast 1 element in s
s + s2
- returns a single sequence of the elements of s followed by the elements of s2
s * n
- returns a single sequence of s repeated n times
s[i]
- returns the element at the index of i
s[i:j]
- returns a slice of s from index i UPTO BUT DOESNT INCLUDE j
len(s)
- returns the number of elements in s
s.index(x)
- returns the index of the first x in s
s.count(x)
- returns the number of instances of x in s
Lists
To sort Lists, python provides 2 different options
my_list = [1,5,3,4,2]
my_list.sort() #sorts the list in ascending order
#stores lists of strings alphabetically
#[1,2,3,4,5]
Key parameter: allows us to pass in a function which can serve as a key for the sort comparison
my_list = ["hello", "tie", "Bob the builder"]
#what if we want to sort by length of the string
#we use the key parameter
my_list.sort(key = len)
#["tie", "hello", "Bob the builder"]
Sorted:
This method should be used when you want to preserve the integrity of the original list
It can use keys also to sort accordingly
my_list = [4,5,2,3,1] sorted_list = sorted(my_list) #to pass in key parameters, you place them as the arguments after list sorted_list = sorted(my_list, key=len)Adding and Modifying Elements in list
my_list = [0,1,2,3] my_list[0] = "bob" #This will update the 0 in the list to "bob" #["bob", 1, 2, 3] #To add to a list, there are 2 ways my_list.append(4) #takes thr argument of what you want to append #["bob", 1, 2, 3, 4] #only appends to the end of the list my_list.insert(1, "hello")#takes 2 arguments. the first is the #index to insert the value. If there is a value at the index #it will be placed before the value. The second is the value to insert #["bob", "hello", 1,2,3,4]Removing from Lists: There are 4 options
#del() removes elements from a list, specified by an index or range #list.pop() removes and returns the element at the index #passed in as an argument. If not argument, removes and returns #the last element in the list #list.remove() removes the element passed in as an argument by #searching for it in the list #list.clear() erases all of the values of a listRanges take some arguments to make it easier to make suing the range() contructor
range(4) #0,1,2,3 range(1,4) #start value and end value gives us 1,2,3 range(0,6,2)#start value, end value, step size = 0,2,4
List Comprehensions
If the contents of a for loop are straightforward, then we can rewrite them in 1 line
my_list = list() for n in range(1,11): my_list.append((n * n)-1) #instead using list comprehensions you can put it in 1 line my_list = [(n *n) -1 for n in range(1,11)] #The syntax is as follows new_list = [optional operation(item) for item in range/oldlist if optional consition == true]
Generator Expressions
Very similar to list comprehensions and have almost identical syntax.
Used to produce iterable objects in a single line
Uses parenthesis instead of square brackets
Doesn't immediately create a new list but saves the data to create a new list at a later time.
Dictionaries
my_dict = { "key 1": "value 1" 2.0: "value 2"In dicts, an immutable key is mapped to an arbitrary value. Similar to JSON Objects
Dictionaries are best used when there is a fixed name or value that we want to associate with a piece of data
Dictionaries are used as a replacement for switch/case statements
def pour_coffee(size): size_to_ounce_map = { "tall": 12 "grande": 16 "venti": 20 } return size_to_ounce_map[size] #This function will return the int that is associated with the size #that is passed into the function when called. #Easier then using if/else statementsGetting Data:
Use dict.get() instead of using the square bracket notation.
Using get takes 2 parameters, the key you're searching for and the second optional is a default value for your search
Using get is the best way to retrieve values from a dictionary if you need to avoid KeyError exceptions
def pour_coffee(size): size_to_ounce_map = { "tall": 12 "grande": 16 "venti": 20 } return size_to_ounce_map.get(size, "please enter a valid size") #What this is doing is if the size isn't found in the dict, instead #of returning an error or None, it returns the default statement #which is the second argument in get()Setting Data:
The simplest way is reassigning the value by passing the key in bracket notation
You can also use the update method
used to set large amounts of data within a dictionary
It can update and add new items to the dictionary simulataneously
Iterating over arrays using dict.items()
my_dict = { "a": 1 "b": 2 "c": 3 } [key for key in my_dict] #['a', 'b', 'c'] [my_dict[key] for key in my_dict] #[1,2,3] #You can use dict.items() to access both key/value pairs #or use them individually [item for item in my_dict.items()] #[('a':1),('b':2),('c':3)] [key for key, value in my_dict.items()] #['a','b','c'] [value for key, value in my_dict.items()] #[1,2,3]
Sets:
Set elements are unique. No duplicates
elements are unordered. Cannot be accessed by indexes
Uses curly brackets like dictionaries but if you try to create an empty set with curly brackets, python will read it as a dictionary.
- Instead you need to use the set contructor set()
There are many things sets are used for
my_list = [1,3,2,4,2,3] set(my_list) #{1,2,3,4} #you can do the same for strings and it will show each individual #letter being used in the sentence We can compare sets to see if 2 different collections have the same number set(range(1,10)) = set([1,2,3,4,5,6,7,8,9]) #true If sets aren't identical, we can use the & operator to see what they have in common' set_1 = {1,2,3} set_2 = {3,4,5} set_1 & set_2 #3 We can check for differences also set_1 - set_2 #1,2 set_2 - set_1 #4,5