- Version: 0.0.1
- Author:
- Nathan Nellans
- Email: me@nathannellans.com
- Web:
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.
# creating variables and assigning valuesvar_name: typeHint="value": typeHintis 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
- Helpful for complex types like:
= "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# 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)# 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")# 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)# 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)# 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()# 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 = ()
- The exception is creating an empty tuple, where parenthesis are required:
# 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
# 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
| Type | Example | Ordered | Mutable 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
deffunction_name(param1: typeHint=defaultValue, param2: typeHint, param3) ->typeHint:
"""documentation string"""dostuffreturnsomething- For naming, use
lowercase_with_underscoresfor functions and methods - Params are optional
: typeHintfor params are optional- Default values for params are optional
-> typeHintfor the function is optionaltypeHintcan beNoneif the function returns nothing
- docstring is optional
deffunction_name(*args):
dostuffusingargs[2]*argsrepresents any number of positional parameters- all values will be stored in a tuple named
args argsis convention, but any name can be used here
deffunction_name(**kwargs):
dostuffusingkwargs["key"]**kwargsrepresents any number of named arugments (keywords)- all keys & values will be stored in a dict named
kwargs kwargsis convention, but any name can be used here
To-DO
TO-DO
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 listifcondition:
dostuffelifcondition:
dostuffelse:
dostuff# shortened, single-line if statementifcondition: doonecommand# condensed if/else statement, aka ternary operator"trueValue"ifconditionelse"falseValue"- The
elifandelsesections are optional
matchexpression:
casepattern:
dostuffcasepatternA|patternB|patternC:
dostuffcasepatternifcondition:
dostuffcase _:
catch-all, wildcardcase# 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# continues as long as condition is truewhilecondition:
dostuffcontinueend the current loop iteration, start the next iterationbreakend the loop altogetherelsesee 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:
dostuffTO-DO
TO-DO
- Popular package registry: PyPI
PythonPackageIndex- https://pypi.org
- 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
importthe package into your program (see below)
- Python comes with many modules, but not all are loaded by default
- Note: It is customary to place all
importstatements at the beginning of a script import random- Use a function from the module:
random.choice()
- Use a function from the module:
import random as alias- Makes the
randommodule available under an alias - Use a function from the module's alias:
alias.choice()
- Makes the
from random import choice, randint- Imports only specific function(s) from the
randommodule into the current namespace - No longer requires the use of the
random.namespace - Use the imported functions:
choice()orrandint() from random import *- Imports all functions from the
randommodule into the current namespace - In general, don't do this
- Imports all functions from the
- Imports only specific function(s) from the
from random import choice as alias- Imports a specific function from the
randommodule 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()
- Imports a specific function from the
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:
commandstotryexceptErrorType:
commandstorunifthegivenErrorTypeisthrownelse:
commandsthatrunifthetrywassuccessful