Skip to content

Latest commit

History

24 Commits

Folders and files

NameName
Last commit message
Last commit date

Repository files navigation

Python Guide (WIP)

Important

This is an advanced guide and assumes you already know the basics of Python. Think of this more like an advanced cheat sheet. I went through various sources, captured any notes that I felt were important, and organized them into the README file you see here.

Warning

This is a live document. Some of the sections are still a work in progress. I will be continually updating it over time.

Tip

AI was not used in the creation of this guide.


Variables

# creating variables and assigning valuesvar_name: typeHint="value"
  • : typeHint is optional
    • Helpful for complex types like: var_name: dict[str, tuple[int,int,int]]
      This would be a dict with strings for keys, and tuples containing 3 integers as values
  • = "value" is optional
    • You can declare a variable without a value. However, you can't use that variable until you assign a value to it
# assign the same value to multiple variables at oncevar_name1=var_name2=var_name3="some value"# assign a seperate variable to each value from an iterable (unpacking)iterable= ["value1", "value2", "value3"]
var1, var2, var3=iterable

Data Types

String: str

# enclosed with single or double quotesvar_name="this is a string"var_name='this is also a string'# multi-line strings can be created with triple quotes (single or double quotes)var_name="""this is amulti-line string"""var_name="""\add the slash as shown aboveand the initial new line will not be included"""# raw strings leave everything intact, and do not support escape sequencesvar_name=r"This is a raw string"# precede the string with an r or R# formatted strings (f-string) allow interpolation as well as many other modifications (TO-DO)var_name=f"This is {another_var} inside a string"# precede the string with an f or F# convert other data types to a string with str()var_name=str(int_var)

Integer Number: int

# un-quoted whole numbers, can be positive or negativevar_name=234# for better readability, you can optionally use _ as a thousands separatorvar_name=1_000_000# convert other data types to an integer with int()var_name=int("40")

Floating-Point Number: float

# un-quoted numbers with a decimal point, can be positive or negativevar_name=37.33# for better readability, you can optionally use _ as a thousands separatorvar_name=3_000.25# convert other data types to a floating-point number with float()var_name=float(31)

Boolean: bool

# un-quoted True or False literals, capitalization requiredvar_name=Truevar_name=False# convert other data types to a boolean with bool()# any value that is empty or zero will be converted to False# anything else will be converted to Truevar_name=bool(0)

List: list

# square brackets surrounding comma-separated valuesvar_name= ["value", 356, True, "fourth"]
# use a single value from a list by referencing its indexlist_name[3]
# convert other data types to a list with list()# TO-DO# add an value to the end of the listlist_name.append("new value")
# remove the first matching valuelist_name.remove("value")
# remove a value by indexdellist_name[3]
# find the number of items in a listlen(list_name)
# sort a listlist_name.sort()
list_name.sort(reverse=True)
# reverse the entries in a listlist_name.reverse()

Tuple: tuple

# parenthesis surrounding comma-separated valuesvar_name= ("value", 356, True, "fourth")
# use a single value form a tuple by referencing its indextuple_name[2]
# convert other data types to a tuple with tuple()# TO-DO
  • The values in a Tuple can not be changed, added, or removed
  • The parenthesis are optional, as the comma is what actually creates the Tuple
    • The exception is creating an empty tuple, where parenthesis are required: var_name = ()

Set: set

# curly brackets surrounding comma-separated valuesvar_name= {"value", 356, True, "fourth"}
  • The values in a Set can not be duplicated, they must be unique
  • The values in a Set are not ordered, and therefore do not have indexes
  • The values in a Set can not be changed. However, values can be added, or removed

Dictionary dict

# curly brackets surrounding key/value pairs, which are separated by commasvar_name= {
"key1": "value",
"key2": 356,
"key3": True,
"key4": "fourth"
}
# use a single value form a dictionary by referencing its indexdict_name["key2"]
# find the number of kv pairs in a dictlen(dict_name)
# remove a kv pair by indexdeldict_name["key"]
  • The keys in a Dictionary can not be duplicated, they must be unique

Comparison of Collection & Mapping Types

TypeExampleOrderedMutable
Values
Add/Remove
Values
Duplicates
list['value', 'value']
(number index)
tuple('value', 'value')
(number index)
🔴*🔴*
set{'value1', 'value2'}🔴🔴🔴*
dict{'key1':'value', 'key2':'value'}
(key index)
keys: 🔴
values: ✅

* = defining feature


Functions

deffunction_name(param1: typeHint=defaultValue, param2: typeHint, param3) ->typeHint:
"""documentation string"""dostuffreturnsomething
  • For naming, use lowercase_with_underscores for functions and methods
  • Params are optional
    • : typeHint for params are optional
    • Default values for params are optional
  • -> typeHint for the function is optional
    • typeHint can be None if the function returns nothing
  • docstring is optional
deffunction_name(*args):
dostuffusingargs[2]
  • *args represents any number of positional parameters
  • all values will be stored in a tuple named args
  • args is convention, but any name can be used here
deffunction_name(**kwargs):
dostuffusingkwargs["key"]
  • **kwargs represents any number of named arugments (keywords)
  • all keys & values will be stored in a dict named kwargs
  • kwargs is convention, but any name can be used here

Documentation Strings

To-DO

Lambda Functions

TO-DO


Comparison Operators

a==b# equal toa!=b# not equal toa>b# greater thana>=b# greater than or equal toa<b# less thana<=b# less than or equal to# and, or, nota==bandc==d# both statements must be truea==borc==d# at least one of the statements must be truenota==b# the statement must not be true# comparison operators can be chained togethera<b<=c# this is equivalent to: a < b and b <= c# checking for a value in a list'value'inlist_variable# returns true if the value is in the list'value'notinlist_variable# returns true if the value is not in the list

Conditional Logic

if Statement

ifcondition:
dostuffelifcondition:
dostuffelse:
dostuff# shortened, single-line if statementifcondition: doonecommand# condensed if/else statement, aka ternary operator"trueValue"ifconditionelse"falseValue"
  • The elif and else sections are optional

match Statement

matchexpression:
casepattern:
dostuffcasepatternA|patternB|patternC:
dostuffcasepatternifcondition:
dostuffcase _:
catch-all, wildcardcase

Loops

for Loops

# loop through a list, dict, or strforiteratorinsequence:
dostuffusingiterator# loop 10 timesforiteratorinrange(10):
dostuffusingiterator# loop through a list with index and valueforindex, valueinenumerate(listVariable):
dostuffusingindex/value# loop through a dict with key and valueforkey, valueindictVariable.items():
dostuffusingkey/value# loop through a dict's keysforkeyindictVariable.keys():
dostuffusingkey# loop through a dict's valuesforvalueindictVariable.value():
dostuffusingvalue

while Loops

# continues as long as condition is truewhilecondition:
dostuff

Special Loop Statements

  • continue end the current loop iteration, start the next iteration
  • break end the loop altogether
  • else see below
# 'else' statements can optionally be used in 'for' loops that use breakforiteratorinsequence:
ifcondition:
breakdostuff# when all iterations are successful, and no break occurredelse:
dostuff# 'else' can optionally be used in 'while' loops that use breakwhilecondition:
ifcondition:
breakdostuff# when all iterations are successful, no break occurred, and the while condition is now falseelse:
dostuff

List Comprehensions

TO-DO

Dict Comprehensions

TO-DO


Imports, Modules, Packages

Packages

  • Popular package registry: PyPI
  • Popular package manager: pip
    • The latest versions of Python come with pip
    • Install a package: pip install packageName
      • By default, pip fetches packages from PyPI
      • After install, you can import the package into your program (see below)

Modules (aka Libraries)

  • Python comes with many modules, but not all are loaded by default
  • Note: It is customary to place all import statements at the beginning of a script
  • import random
    • Use a function from the module: random.choice()
  • import random as alias
    • Makes the random module available under an alias
    • Use a function from the module's alias: alias.choice()
  • from random import choice, randint
    • Imports only specific function(s) from the random module into the current namespace
    • No longer requires the use of the random. namespace
    • Use the imported functions: choice() or randint()
    • from random import *
      • Imports all functions from the random module into the current namespace
      • In general, don't do this
  • from random import choice as alias
    • Imports a specific function from the random module into the current namespace, but makes it available under an alias
    • No longer requires the use of the random. namespace
    • Use the aliased function: alias()

Classes

classsome_name:
# instance method# used when creating a new instance/object of the classdef__init__(self, parameter1, parameter2, parameter3=default):
# assigning parameter values to instance variables (self._xxx)ifnotparameter1:
raiseValueError(“parameter1isundefined”)
ifparameter2notin [“value1”, “value2”]:
raiseValueError(“invalidvalueforparameter2”)
self._parameter1=parameter1self._parameter2=parameter2self._parameter3=parameter3# or, if you are using "setters"parameter1(parameter1)
parameter2(parameter2)
# instance method# used when printing an instance/object of the classdef__str__(self):
returnf”{self._parameter1} andalso {self._parameter2}”
# custom instance methoddefyourCustomMethod(self, parameter1):
commandsreturn ...
# “getter” for parameter1@propertydefparameter1(self):
returnself._parameter1# “setter” for parameter1@parameter1.setterdefparameter1(self, parameter1):
ifparameter1notin [“one”, “two”, “three”]:
raiseValueError(“invalidvalueforparameter1”)
self._parameter1=parameter1# class variablesclass_var1="value"class_var2="value"# class methods@classmethoddefmethod_name(cls, parameter1):
commandsreturn ...

Try & Except

try:
commandstotryexceptErrorType:
commandstorunifthegivenErrorTypeisthrownelse:
commandsthatrunifthetrywassuccessful

About

Python Guide

Topics

Resources

Stars

0 stars

Watchers

1 watching

Forks

Releases

Sponsor this project

Used by

Contributors