Basics
Variables
Places to store data and modify it. They are classes and have methods.
- https://www.tutorialspoint.com/python/python_variable_types.htm
- https://www.w3schools.com/python/python_datatypes.asp
- https://www.youtube.com/watch?v=XKHEtdqhLK8
Types of variables
- Must start with a letter or the underscore. Can not start with a number.
- Can only contain alpha-numeric characters and underscores (
A-z
,0-9
, and_
). - They are case sensitive.
True or false
Comparison Operators
Assignment Expressions
x := y # Becomes
x += y # In-place add
x -= y # In-place minus
x *= y # In-place multiply
x @= y # In-place matrix multiply
x /= y # In-place division
x //= y # In-place int division
x %= y # In-place mod
x &= y # In-place bitwise and
x |= y # In-place bitwise or
x ^= y # In-place bitwise xor
x <<= y # In-place left shift
x >>= y # In-place right shift
x **= y # In-place power
env_base = os.environ.get("PYTHONUSERBASE", None)
if env_base:
return env_base
# Instead
if env_base := os.environ.get("PYTHONUSERBASE", None):
return env_base
Weird things
Multiple assignment
*
can be at any place but only once.
Data types
Check if a variable is a certain type.
Variable types are:
- basestring
string and unicode
- str
string
- int
integer
- bool
boolean
- float
float
Other data types are: - https://www.mssqltips.com/sqlservertip/7126/learn-python-data-types/ - https://www.mssqltips.com/sqlservertip/7127/python-list-tuple-range-dictionary-and-set-data-type-examples/
Lists []
- Ordered
- Indexed
- Mutable
- Non-homogeneous
- Allows duplicates
Dynamically sized array.
Tuples
- Ordered
- Immutable
- Non-homogeneous
- Allows duplicates
Collection of various objects separated by commas.
Sets
- Mutable
- Unordered
- Un-indexed
- Non-homogeneous
- Does not allow duplicates (unique)
- Iterable
- Nice for searching
- Faster than the rest
Unordered collection of data types.
Dictionary
- Mutable
- Unordered
- Unique key (not duplicated)
- Non-homogeneous
Unordered collection of various data types. Used for maps.
my_dic = dic()
empty_dic = {}
my_dic = {"a":10,1:"b",3.5:"z"}
print(my_dic["a"]) # 10
print(my_dic[3.5]) # "z"
if "b" in i:
print(i["b"])
Dictionary methods
Mutable or immutable
Source List of immutable types:
List of mutable types:
Casting
Explicitly specify the type of the variable.
Convert from one type to other (int
to str
):
Strings
String slicing
indexing[]
[start:stop:step]
-
slice()
-
The indexes as exclusive,
[0:8]
will go from 0 to 7. - Every character has a positive and a negative index.
Indexing. You need to do something with the resulting string.
print("string"[:3]) ## "str"
s = "The quick brown fox jumps over the lazy dog"
s[0] ## First letter
s[-1] ## Last letter
s[0:3] ## First 3 letters. From 0 to 2
s[:3] ## First 3 letters (short). From 0 to 2
s[-3:] ## Last 3 letters
s[::2] ## Print even characters
s[::-1] ## Reverse the string
Slicing
s = "The quick brown fox jumps over the lazy dog"
print(s[slice(1)]) ## First letter
print(s[slice(0,3)]) ## First 3 letters
print(s[slice(4,-4)]) ## "quick brown fox jumps over the lazy"
print(s[slice(-1)]) ## Everything except the last letter
print(s[slice(0,len(s),2)]) ## Even characters
p = slice(0,3)
print(s[p])
Example
s = "The quick brown fox jumps over the lazy dog"
p = s.find(" ") ## Find the first space
print(s[:p]) ## Print the first word
Conditional statements (ternary operators)
>
Greater than>=
Greater than or equal==
Equals!=
Not equals<
Less than<=
Less than or equal
They resolve to True
or False
.
Example
Logical operators
Used to combine conditional statements.
and
both statements have to beTrue
or
only one statement has to beTrue
not
invert
Example. max_temp
has to be greater than 22 and rain
has to be False
if...elif...else
One line if
One line if...else
One line if...elif...else
b = 7
a = "neg" if b < 0 else "pos" if b > 0 else "zero"
if b < 0:
a = "neg"
elif b > 0:
a = "pos"
else:
a = "zero"
Nested if
. if
statement inside an if
statement.
Loops
For
radio_names = []
for s in radio_stations:
radio_names.append(s[0])
## Equal to
radio_names = [s[0] for s in radio_stations]
Classes
Methods
Function which is a member of a class. A function inside a class
Find all the methods for str()
https://www.askpython.com/python/examples/find-all-methods-of-class
Built-in Functions
type()
dir()
id()
getattr()
hasattr()
globals()
locals()
callable()
Functions
Multi-Return
def test(par1,par2,par3):
return par1,par2,par3
name,surname,birth = test('john','smith',1976)
print(name)
print(surname)
print(birth)
Default value for arguments in a function
def test(par1,par2=None):
ret1 = par1
ret2 = par2
return ret1,ret2
name,surname = test('john','smith')
print(name)
print(surname)
name,surname = test('john')
print(name)
print(surname)
n
arguments for a function.
def test( par1='', **atr ):
return par1,atr
name,atrs = test('john',height=180,country='Italy',city='Bonachello')
print(name)
print(atrs)
for key, val in atrs.items():
print('[%s] => [%s]' % (str(key), str(val)))
print(atrs['country'])
name,atrs = test(height=180,country='Italy',city='Bonachello')
try:
if atrs['city']:
print(f"The city is {atrs['city']}")
except KeyError:
print("There is no city")
try:
city = atrs['city']
except KeyError:
print("There is no city")
else:
print(f"The city is {city}")
try:
city = atrs['city']
except KeyError:
city = False
Weird things
Dynamically create variables named as the values in a list
Variable names can not start with an int, that is why the f"id_{i}"
.
class Test:
def __init__(self,id,type,price,name="null"):
self.id = id
self.type = type
self.price = price
self.name = name
ids = [1234,2345,3456,4567]
## Assign
for i in ids:
globals()[f"id_{i}"] = Test(i,"type",1.2,"name")
## Print all
for i in ids:
print(globals()[f"id_{i}"].id)
print(globals()[f"id_{i}"].type)
print(globals()[f"id_{i}"].price)
print(globals()[f"id_{i}"].name)
## Print individually
print(id_1234)
print(id_2345)
print(id_3456)
print(id_4567)
Modules
Web server
Python 3
Python 2
Conventions and Terminology
- PEP: Python Enhancement Proposals
Run old versions of python.
I found to be easiest with Conda.
conda create -n your_env_name python=3.9
conda activate your_env_name
conda install package_name
pip install package_name
SSL Certificates
For some reason it does not use the ones installed in the system.
conda config --set ssl_verify <pathToYourFile>.crt
pip install flask cassandra-driver --trusted-host pypi.org --trusted-host pypi.python.org --trusted-host files.pythonhosted.org
pip config --global set global.trusted-host "pypi.org pypi.python.org files.pythonhosted.org"
pip install flask --cert=/usr/local/share/ca-certificates/proxy.crt