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
a = 1 # integer
b = 2.5 # float
c = "3" # string
d = '4' # string
e = False # boolean
- 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
a = 0 ## False
a = 1 ## True
a = "" ## False
a = "a" ## True
Comparison Operators
x == y # Equals
x >= y # Greater-than-or-equal-to
x <= y # Less-than-or-equal-to
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
n = []
n += range(3)
def query(url):
r = requests.get(url)
if r.status_code == 200:
return json.loads(r.text)
---
def query(url):
if 200 == (r := requests.get(url)).status_code:
return json.loads(r.text)
Multiple assignment
a = b = c = 7
d, e, f, g = 5, 6.7, "8", True
h,i,j = (3,2,1)
tuple = [1, 0.6, "a"]
l, m, n = tuple
*
can be at any place but only once.
a, b, *c, d = [1,2,3,4,5,6,7]
print(a) ## 1
print(b) ## 2
print(c) ## [3, 4, 5, 6]
print(d) ## 7
Data types
variable = "Hello"
print(type(variable)) ## <class 'str'>
Check if a variable is a certain type.
if isinstance(variable, str):
print(f"'{variable}' is a string")
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.
["a",1,3.5]
my_list = list()
empty_list = []
Tuples
- Ordered
- Immutable
- Non-homogeneous
- Allows duplicates
Collection of various objects separated by commas.
("a",1,3.5)
my_tuple = tuple()
empty_tuple = ()
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.
{"a",1,3.5}
my_set = set()
set.union(my_set2)
set.intersection(my_set2)
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
i = {"a":1,"b":2,"c":3,"d":4,"e":5,"f":6,"g":7}
for j in i:
print(j) ## Print the keys
for k,v in i.items():
print(f"{k}:{v}")
for j in i.values():
print(j)
for j in i.keys():
print(j)
print(i)
i.pop("d")
print(i)
print(i["a"])
print(i.get("a"))
Mutable or immutable
Source List of immutable types:
int, float, decimal, complex, bool, string, tuple, range, frozenset, bytes
List of mutable types:
list, dict, set, bytearray, user-defined classes
Casting
Explicitly specify the type of the variable.
str(7) ## "7"
float(7) ## 7.0
int(7.7) ## 7
bool(0) ## False
Convert from one type to other (int
to str
):
a = 3 ## int
print("a is " + str(a)) ## Concadenate two strings
Strings
a = "" ## False
a = "a" ## True
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
age = 45
if age > 34:
print("You are older than 34")
age >= 34 ## Prints "True"
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 not (max_temp > 22 and not rain):
print("It is going to be a cold and rainy")
if...elif...else
One line if
a = 2
b = 20
if a < b: print("a is smaller than b")
One line if...else
b = 7
a = "positive" if b >= 0 else "negative"
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.
if x > 10:
if x == 45:
print("It is 45!")
else:
print("Is bigger than 10")
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()
print(dir(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 -m http.server
python -m http.server --cgi
Python 2
python -m SimpleHTTPServer
Conventions and Terminology
- PEP: Python Enhancement Proposals