Summary Python
Summary Python
DICTIONARIES
dict.items() Returns a list with the format [(key1,
value1), (key2, value2),…]
dict.keys() Returns the list of the keys
dict.values() Returns the list of the values
dict.copy() Copy of the dictionary, they do not point
the same memory address
dict.pop(key1) Delete the key1-value1 pair.
Attention! key1 must exist!
dict.clear() Delete all elements of the
dictionary
LOOPS
for i in sequence:
# body of the loop!
# i gets the values of the sequence!
# do not forget tabs!
# do not forget the colon!
# Sequences are lists and strings!
# Here the loop ends
while condition:
# body of the loop!
# do not forget tabs and colons!
# Here the loop ends
break Get out of the loop
continue Jump to the next
iteration
pass It does not do anything
List comprenhension:
[x*x for i in [1, 2, 3, 4]] FUNCTIONS
FLOW CONTROL
Result: Def func_name(var1, var2):
If condition:
[1, 4, 9, 16] “”” Docstring
# if the condition is satisfied, Attention to tabs!
“””
else:
# Body of the function!
# if the condition is not satisfied, Attention to tabs!
# Do not forget tabs!
# Do not forget colon
IMPORT LIBRARIES/MODULES return result # optional
import random random.uniform(0, 10) lambda x: x * x
import random as rd rd.uniform(0, 10)
from random import uniform uniform(0, 10) #Attention! only MUTABILITY
uniform is available, the rest of Integers Immutable
methods/objects are not Float Immutable
from random import* uniform(0, 10) # Every Boolean Immutable
method is available Lists Mutable
Tuples Immutable
Dictionaries Mutable
FILE MANAGEMENT
File = open(“myfile.txt”, 'r') Open myfile.txt file as read-only
File = open(“myfile.txt”, 'w') Open myfile.txt file as editable
File.close() Close file both as read-only and editable
File.write(str1) Write str1 to the file.
File.readlines() Returns a list that contains all lines of the file
for line in File: Go through all lines of the file. Work with line variable
PYTHON CHEAT SHEET
CLASSES
class myclass (object):
“””Docstring
“””
def __init__(self,atr1, atr2):
# Here the builder begins
self.atr1 = atr1
self.atr2 = atr2
def method1(self):
MAGIC FUNCTIONS # body of method1
return (self.atr1 + 2)
%clear Clear the terminal, not the objects
%exit Delete the objects def method2(self):
# body of method2
%run file1.py Run the script
Obj1 = myclass(10, 20) Define and initialize
%history Command history
the object
%cd “folder” Switch to the folder directory
Obj1.atr1 Access to the
%”command”? Help
attributes
PIP
Obj1.method1() Access to the
!pip install module Install module/library
methods
!pip upgrade module Upgrade module/library
!pip show version Show version of module/library
SLICING
sequence[0] First element
sequence[-1] Last element
sequence[:] All elements
sequence[a:b] Elements within the [a, b) interval
sequence[a:b:p] Elements within the [a, b) interval
with p step