Please enable JavaScript.
Coggle requires JavaScript to display documents.
Python, interpreter, Language, Modules, ecosystem, OOP, https://www…
Python
interpreter
python --version
python hello.py
which python
Language
types
common
numeric
float - IEEE 754 64-bit double
int -
arbitrary
length signed integer
strings
create a string
'Foo' # single quoted string (equivalent)
"Hello 'Foo'" # nested quotes, no need to escape
""" Multi-line """
"Foo" # double quoted string
inmutable sequences
slicing
slice operator
y = x[::-1] # -1 steps backwards, y is now 'dlroW olleH'
Defaults are 0 =
start index
, N =
count
and 1 =
step
(skip).
y = x[4:-3] # slice from the 4th element to the 8th element
get length - len
access
indexing
reverse indexing
bool True|False
collections
tuples
x =
(1, 2, 3, 4)
inmutable sequences of any type
ranges
sequences of int
x = range(1,4) # create a range from 1 (inclusive) to 4 (exclusive)
y = range(1,5, 2) # create a range from 1 (inclusive) to 5 (exclusive) with step size 2
lists
mutable sequences
x =
[1, 2, 3, 4]
# create a list and assign to x
built-in functions
del x[0] # delete the zeroth element in x
len(x)
slice operator
indexed access and reverse indexed access
dictionaries
mutable map
of key/value pairs
sets
unordered collection of unique values
x =
{1, 2, 3, 5, 1, 2}
methods
.discard
.clear
.add
.update - adds array of elements to set
operators
arithmetical: +,-,
, /, // (integer division), %, *
(power)
comparison (by
value
): >, <, ==, !=, >=, <=
logical: and, or, not
compound assignments: +=, -=,
=, /=, //+, %=,
*=, //=, %=,
=
bitwise: & (AND), | (OR), ^ (XOR), ~(NOT), << (shift bits left), >>(shift bits right)
string: <,>,(compare unicode values), + (concatenation), * (multiply a string), in (search)
hints/annotations
generics
flow control
if/else
if
true:
....print('yes')
elif
:
....pass
else
:
....pass
loops
for
i in
range
(10):
....print(i)
for
i,v in
enumerate
((1,2,3,4,5)): # enumerate elements in tuple
....print(i)
while
a > 0:
....print(a)
....a//10
exceptions
raise Exception("Error message")
try/except
try: # try block
....raise Exception("Error message") # raise an exception
except Exception as # catch the exception
....print(e)
finally:
....print("done!")
functions
built-in functions
numerical
round() - rounds number of floating point value
hex(), bin() - converts decimal to hexadecimal and binary value
divmod() - computes quotient and remainder after division of 2 numbers
sequence
sorted() - sorts list of values in ascending order
len(), range(), input(), print()
reversed() - returns reversed list
is...
isalnum()
# returns true if all characters in the string are alphanumeric
isalpha()
isdigit()
islower()
isspace() # returns True if all characters in the string are white spaces. The white spaces include simple spaces, tabs, and newline characters.
istitle() # returns True if the string follows the rules of the title?
isupper()
case change
capitalize()
lower()
swapcase()
title()
upper()
search
endswith()
find()
rfind()
count()
replace()
startswith()
value-inserting
append()
copy()
extend() # appends multiple elements to the end of the list. Can be used to append a list to another.
insert() # adds an element at a specified position in the list
value-removing
clear()
pop() #removes an element from a specified position in the list
remove() #removes the first occurence of a speciried value from the list
search-related
count()
index()
user defined
lambdas
(anonymous)
tripe =
lambda
num : num * 3
use when a function requires another
function as a argument
e.g. with built-in map(function, list) - returns new list
e.g. with built-in filter(function, list) - returns new list containing items satisfying function
named
def add(n1,n2)
.... return n1+n2
Modules
built-in
math
csv, json
sys, os
urllib
Python file imported by another Python file
# mymodule.py file
def test():
....print('test')
# main.py file
from mymodule import test
test()
packages
mypackage
|--- __init__.py
|--- module1.py
|--- module2.py
ecosystem
Poetry
tut
what for
dependencies management
isolate applications envs -
virtualenv
commands
poetry new --src project
# create a new poetry project
initialises pyproject.toml file
initialises src and tests folders because of --src flag
poetry add pydantic
# adds project dependency
updates
poetry.lock
poetry add pytest --group dev
# adds dev group project dependency
poetry shell
#enters poetry virtual environment
poetry env info
# check virtual environment info
poetry show
# shows packages information
poetry show pydantic
# shows pydantic package information
poetry remove pydantic
# removes pydantic package
alternatives
conda
pip
pyenv
what for
sets global Python version per user-basis
provides support for per-project Python versions
allows Python version override through environment variable
commands
pyenv root
#shows directory where Python versions are installed
pyenv local
#shows/set local/application specific Python version
pyenv local 3.9.4 #sets local Python version to 3.9.4
pyenv version
#shows specific version + origin
pyenv versions
#shows available versions
pyenv uninstall
pyenv install --list
#shows available Python versions
pyenv global 3.9.17
#sets Python global version
alternatives
pipenv
Ipython
- friendly interpreter with syntax highlight
OOP
syntax
# create
class attributes
ID, salary and department
class Employee:
....ID = None
....salary = None
....department = None
steve = Employee()
steve.ID = 5894;
print(steve.ID)
# define a
class
class Employee:
....pass # pass keyword is a placeholder for future code
# create an
instance
of Employee
steve = Employee()
methods
#
instance methods
class Employee:
....def __init__(self, ...):
........pass
....def tax(self):
........return(self.salary*0.1)
....def dailySalary(self):
........return(self.salary/30)
Steve = Employee(5862, 50000, "IT")
print(Steve.ID)
print(Steve.tax())
#class methods
class Employee:
....classVariable = "demo"
....@classmethod
....def demo(cls)
........return cls.classVariable
#static methods
class Employee:
....@staticmethod
.... def demo()
........print("I am a static method")
access modifiers
public - default: applies all attributes and methods
private - members can be made private by prefixing their names with underscore
__
# define class
initializer
class Employee:
....def
init
(self, ID=None, salary=None, department=None):
........self.ID = ID
........self.salary = salary
........self.department = department
Steve = Employee(5862, 50000, "IT")
print(Steve.ID)
design
Inheritance
Parent/Super/Base class & Child/Sub/Derived class
Child class has all public attributes of parent class.
e.g.
class Vehicle:
....pass
class Car(Vehicle):
...pass
suzukiVitara = Car()
Accessing parent class properties or methods
super()
Types
single
multi-level
multiple
e.g.
class HybridEngine(CombustionEngine, ElectricEngine)
Encapsulation
declare class variables with private access modifier
provide public methods
getters
setters
e.g.
class User:
....def __init__(self, username=None):
........self.__username = username
....def setUsername(self, x):
........self.__username = x
steve = User('Steve')
steve.setUsername("steve')
Polimorfism
class Shape:
....def __init__(self)
........self.sides = 0
....def \getArea(self)
........pass
class Rectangle(Shape):
....def __init__(self, width=0, height=0):
........pass
....def getArea(self):
........return (self.width * self.height)
derived classes can give their own specific implementations to inherited methods without modifying the parent class methods
Operator overloading - Py allows predefined operators override for a specific class
abstract classes
class Shape():
....@abstractmethod
....def area(self):
........pass
allows to define a class interface w/o implementing methods, so that derived can provide specific implementation
cannot be instantiated
https://www.educative.io/path/zero-to-hero-in-python
"In Py everything is an object"
https://www.educative.io/courses/python-quickstart-for-experienced-programmers/the-python-language-4