Skip to content

Syntax

python shebang

#!/usr/bin/env python3
#!/usr/bin/python3

agreements

lower_case_with_underscore     # variables and functions
UPPER_CASE_WITH_UNDERSCORE     # constants
CamelCase                      # class

type casting

int(2.0), str(2), float(2.2)

loops

for i in range(7,0,-1):     #7,6,5......
    pass
    break
    continue
else:
    pass

for item in my_list:
    pass

while i < 3:
    pass

for index,item in enumerate(my_list):
    print(f"index={index} item={item}")

for item in zip([1, 2, 3], ['sugar', 'spice', 'everything nice']):
    print(item)   # set(1,'sugar')


new_list=list(map(sum, zip(my_list,my_list)))
squares=[i**2 for i in my_list]

Conditions

if e == e:
    pass
elif e==a:
    pass
else:
    pass

msg= "test1" if e==a else "test2"

if "item" in my_list:
    pass

Functions

def action(a,b):
    pass
    return

action(a,b)

anonymous lambda functions

sqrs  = lambda x: x**2
print(sqrs(4))

from functools import reduce

n = [1,2,3,4,5]
squares  = list(map(lambda x:x**2,n))
even = list(filter(lambda x : x%2==0,n))
product = reduce(lambda x,y: x*y , n)

Exceptions

try:
  num = 4/2
except ZeroDivisionError:
    pass
except TypeError:
    pass
else:
    pass
finally:
    pass

lists

my_list = ["item",12,true]
my_list.append("item").extend(["item","item"]).sort().insert(5,"item")
my_list += ["item","item"], sorted(my_list), my_list.index("item").count("item").reverse()
del my_list[3], my_list.pop(3).remove("item").clear()
len(my_list), max(my_list), min(my_list), sum(my_list), 
my_list[1],[:3],[5:],[5:1],[:-2],[::-1]

tuples

my_tupla = (1,2,3,4,5)
a,b,c,d,e = my_tupla

my_tupla[::3],[1]

sets

# unique elements
# messy elements 
# quick search

my_set = {1,2,3,4,5,6,7,8,9}
set2 = {"hello",9,3}
print("item" in set2) # false

my_set.add(2).update({11,12,13}).remove(2).discard(1000).issubset(set2)
end_set = my_set.intersection(set2).union(set2).difference(set2)

dictionary

my_dictionary = {"name":"name1", "age":12, "place":"city"}
my_dictionary["name"] = "name2"
my_dictionary["profession"] = "teacher"
del my_dictionary["place"]

print(my_dictionary["nombre"])
print(my_dictionary.keys().values().get("key","not found")).update(other_dictionary)

for key,value in dic.items():
    print(f"key={key} value ={value}")

args and kwargs

def suma(*args):
  return sum(args)
print(suma(1,2,3,4,5))


def Presentacion(**kwargs):
  for clave,valor in kwargs.items():
    print(f"{clave}: {valor}")

Presentacion(nombre="Antony", edad= 23, ciudad = "Peru")
Docs

https://docs.python.org/3/library/functions.html