Python

Python is a high-level, general-purpose programming language known for its readability and simplicity. It can be used for web development, data analysis, automation, artificial intelligence, and more.

height = 40
width = 30
area = height * width
print('The area is', area)

Python CLI

Python Interpreter

python3
python

Python Files

hello_world.py
python3 hello_world.py
python hello_world.py

Printing Code

print("Hello world")

Getting Input

input("What's your name? ")

Python Basics

Comments

# This is a single-line comment

"""
This is a
multi-line comment
"""

Data Types

Check the data type: type()

Check the memory address: id()

# Data Types

- Strings
- Booleans
- Integers - Whole numbers
- Floats - Decimal numbers

# Integers

17
-2048
93_000_000

Integer Methods

# Floats

1.5
3.14159
-3_000.12

Float Methods

# Strings

"G"
"Grant"
"ALL_CAPS!"
'123123abcabc'

String Methods

# Booleans

True
False

Boolean Methods

Lack of a value: None
# Changing Data Types
  - int("30")
  - float("132.5")
  - str(123)

Operators

# Arithmetic Operators
+       Addition
-       Subtraction
*       Multiplication
/       Division
//      Floor division (division but rounds down)
**      Exponential
%       Modulo (remainder after division)

# Logical Operators

and
or
not

# Assignment Operators

=       assignment operator
+=
-=
*=
/=
//=
**=
%=

# Comparison Operators

>
<
>=
<=
==
!=

# Python Boolean Operators

in
is # identity operator

Case

Constants = SCREAMING_SNAKE_CASE

flatcase
kebab-case
snake_case
camelCase
Train-Case
PascalCase

Variables

Variables store values with a label.

age = 30
name = "Grant"

# Slicing Strings

"who goes there"[2:6]
"who goes there"[4:]
"who goes there"[:6]
"who goes there"[1:6:2]

# Escape Characters

\n
\t
\'
\"
\\

Concatenation = Joins strings together
Interpolation

Scope
global var_name

Python Data Structures

Lists (Arrays)

Storing ordered information

list = ['one', 'two', 'three']
array[0]               # access
array[2] = 'changed'   # change
array.append('new')    # add
array.extend([1, 2, 3]) # adds 1, 2, 3 to end
array.insert(1,'new')  # inserts 'new' at index 1
array.clear()          # deletes everything
array.remove("C")      # removes only the first "C"
array.pop()            # remove the last element
array.pop(0)           # remove the value at index 0
del array[2:]          # removes everything after index 2

array.count(1)         # counts the arguments in list
array.sort()           # sorts in ascending order
array.sort(reverse=True) # sorts in descending order

string.split("-")      # splits a string given a delimiter
string.join("hi")      # adds to a string

array.reverse()        # reverses the list
array.copy()           # creates a copy

# Slice / Sub-Selection
list[:3]       # start at 0, stop at 3
list[4:]       # start at 4, stop at end
list[1:5]      # start at 1, stop at 5
list[1:5:2]    # start at 1, stop at 5, step 2

# Nested Lists
arr = [[1,2,3], [1,2,3], [1,2,3]]
arr[2][2]

# List unpacking
user = ["1", "2"]
first, last = user
*others

# Filter
filtered_data = [d for d in data if d["age"] > 25]

filtered_ny = [d for d in data if d["city"] == "New York" and d["age"] > 30]
print(filtered_ny)

Dictionaries (Objects)

Storing unordered information

dictionary = {
  "name": "Grant",
  "age": 30
}
dictionary["name"]        # access
dictionary["age"] = 31     # change
dictionary["state"] = "CO" # add

key in dictionary          # returns true or False
dictionary.get("name")    # returns value or None

dictionary.pop("age")     # removes key and returns value
dictionary.popitem()      # removes most recent addition and returns both key/value
dictionary.clear()        # deletes everything
del dictionary["state"]   # deletes and returns nothing

dictionary.keys()         # returns dict_keys of all keys
dictionary.values()       # returns dict_values of all values
dictionary.items()        # returns dict_items of all pairs/items

dictionary.update({"name": "GDavis"}) # updates or merge existing dictionary
new_dictionary = {**dict1, **dict2}   # creates new dict -
newer_dictionary = dict1 | dict2      # creates new dict - right-side pref

# Nested
produce["coconut"]["producer"] # dict inside a dict
test_scores["Marsha"][0]       # list inside a dict
waitlist[0]["name"]            # dict inside a list

Python Functions

  • Arguments are the actual inputs we provide to a function.
  • Parameters are the placeholders in the function name
# Creating a function
def my_function():
  return 1

# Calling a function
my_function()
# *args = any number of arguments, returns a tuple
# **kwargs = any number of keyword arguments, returns a dictionary

def function(): # default function
  return 1

def function(arg1, arg2): # multiple params
  return arg1 + arg2

def function(arg1=100): # default params
  return arg1

def function(arg1=10.00, tax=19) # keyword args - order doesn't matter
  return arg1

get_total(price=10.99, tax=0.02)

def count_stuff(*args):
  return len(args)
round()
int()
float()
bool()

Python Conditionals

Logic and branches

if age >= 21:
  print("Come on in!")
if age >= 21:
  print("Come on in!")
else:
  print("Go home kid!")
if age >= 21:
  print("Come on in!")
elif age >= 18:
  print("You're an adult but can't drink")
else:
  print("Go home kid!")

Python Loops

Repeating code

  • break - Stop immediately
  • continue - Stops current iteration, but skips the iteration and moves to the next character
count = 0
while count < 10:
    print(count)
    count += 1

word = "Hello"
for item in word:
    print(item)

# Lists
nums = [1, 2, 3, 4, 5]
for num in nums:
    print(num)

for item in range(10,1,-1):
    print(item)

for item in range(5,10):
    print(item)

# Dictionaries
for key, value in test_scores.items():
    print(key, value)

Python Modules

Reusable complex code in files.

# Built-in
import os
import sys
import datetime
import logging
import json
import copy
import random
import math

import thing as other_thing    # rename
from thing import *             # import everything (no object)
from thing import specific_thing # import something specific

# Custom
import name                     # name.py in same repo
from utils import brand_colors, mean

# Third-Party
pypi.org
pip
python3 -m pip install package
python -m pip install pyinstaller
import random

random.randint(1,6)

Python Tuples

Ordered, unchangeable information

t1 = (1,2,3)
t2 = (1,)

t1[0]        # access
t1.index(2)
t1.count(4)

Python Sets

Unordered collections with no duplicated elements

s1 = {1, 2, 3, 4}

s1.add(12)     # add
s1.remove(7)   # remove w/ error
s1.discard(3)  # remove w/o error
s1.clear()     # clears everything

# Operators
left & right   # in common between both
left | right   # everything from both (no dupes)
left - right   # unique only to left

Python Errors

  • Errors - Things are screwed.
  • Exceptions - Things can be fixed. Code stops executing. You can raise an exception.

Raising Exceptions

raise Exception
      raise Exception("Invalid character")
      raise ValueError

Try / Except

try:
          # code that could raise an error
      except:
          # code that runs if an error is raised
try:
          # code that could raise an error
      except ValueError:
          # code that runs if an error is raised
      except EOFError:
          # code that runs if an error is raised

Object-Oriented Programming

Classes

Classes are blueprints or recipes that we create objects from. They define attributes and functionality.

# Class
class Puppy:
  species = 'canine'
  num_dogs = 0

  @classmethod
  def register_stray(cls):
    return cls('unknown', 'unknown', 'unknown', 'unknown')

  def __init__(self, name, breed, location)
    self.name = name
    self.breed = breed
    self.location = location
    self.tricks = []
    Dog.num_dogs += 1

  def bark(self):
    print(f"{self.name} says WOOF!")

  def add_trick(self, new_trick):
    self.tricks.append(new_trick)

# Instantiation
elton = Puppy("Elton", "German Shepherd", "Louisville")
elton.name # 'Elton'
elton.tricks # []

# Instance Methods
elton.add_trick('sit')

# Class Attributes
elton.species # 'canine'
elton.num_dogs #
Dog.num_dogs #

# Class Methods
new_dog = Puppy.register_stray()

# Inheritance
class Lion(Cat):
  def __init__(self, name, pride_name):
    super().__init__(name)
    self.pride_name = pride_name