https://www.youtube.com/playlist?list=PLUl4u3cNGP63WbdFxL8giv4yhgdMGaZNA MIT https://pll.harvard.edu/course/cs50s-introduction-artificial-intelligence-python?delta=0 HARVARD https://www.coursera.org/professional-certificates/google-it-automation?action=enroll https://www.coursera.org/professional-certificates/ibm-data-science
https://www.youtube.com/watch?v=gOdRQsAjQWk&t=544s&ab_channel=PaulAmbrosiussen
Variable = small_letters_snake_code
Clases = HugeLetters
Swaroopch
Jupyter
W3schools
Learnpython
Techbeamers
Logic operators
or, not, and
Reserved Keywords
and, as, assert, break, vlass, continue, def, del, elif, else, except, dinally, for, from, global, if, import, in, is, lambda, not, or, pass, print, raise, return, try, while, with, yield, nonlocal.
Operations order
- Parenthesese
() - Power - Rise to power - exponentiation
**- Power - Multi -
*,/ - Add -
x - Left to right -
Division
divisiontyp1 = 7/2 = 3
divisiontyp2 = 7/2. = 3.5
divisiontyp3 = 7/float(2) = 3.5
Data structures
- Call (use) method on object.
object.method()
foo_int = 3 + 3
foo_float = 3.333
foo_bool = True
foo_bool = False
foo_string = "my string" # immutable
List
List - collection:
- Ordered
- Mutible
- Indexing/slicing
- Allow duplicates.
foo_list = list() # create empty list
foo_list = ['A', 2, True] # list
- Fn:
len() append() # add insert(2,"B") # insert(index,item) pop() # remove remove("A") # clear() # remove all reverse() / sort() / sorted() - Search element:
print(foo_list[1]) a = foo_list[3:] # 3 to end a = foo_list[3::2] # every second from 3 - Loop through list
for i in foo_list: # Loop through list print(i) - Check if on list
if 'A' in foo_list: print('yes') else: print('no')
List 2d
foo_grid = [[00,01,02], [10,11,12], [20,21,22]]
- Get Cell
print(foo_grid[1][1]) # 11 - Loop through
for row in foo_grid: for col in row: print(col)
Tuple
Like list - (less storage, quicker to accces, more efficient. )
- Ordered
- Immutable !!!
- Indexing/slicing
- Allow duplicates.
- cannot assign items like list.
foo_tuple = (3, 3.3, 3+3j, 'A') # mixed
foo_tuple = 3, 3.3, 3+3j, 'A' # mixed
- Index
foo_tuple = tuple([1,2,3]) # tuple from list foo_tuple = tuple(foo_list) item = foo_tuple[2] # index. item = foo_tuple[-1] # last item = foo_tuple[-2] # last -1 - Check
if 'A' in foo_tuple: print('yes')foo_tuple.count('A') # 1 foo_tuple.index('A') # 4
Set
Dictionary without values
- not ordered
- Mutible
- No Indexing/slicing
- Dont allow duplicates.
foo_set = {}
a = frozenset([1,2,3,4])
Dictionary
Hashmap - that store Key & Value
foo_dict = {'letter' : 'A'. 'number' : 3}
foo_dict = dict(letter="A", number=3)
- Delete
del foo_dict['number'] foo_dict.pop('number') foo_dict.popitem() # last item - Check
if 'number' in foo_dict: print(number) - Example
dict = { "Jan":"January", "Feb":"February", "Mar":"March" } print(dict["Mar"]) # March print(dict.get("Jan")) # January print(dict.get("Foo", "Not a valid key")) # with default value # Not a valid key - Counters
foo= dict() foo['a'] = 1 foo['b'] = 1 print(foo) # {'a':1,'b':1} foo['a'] = foo['a'] + 1 # counter print(foo) # {'a':2,'b':1} .getmethod on dictionaryif foo_key in foo: x = foo[foo_key] else: x = 0 x = foo.get(name,0)for foo_key in foo: foo[foo_key] = foo.get(name,0)+1 # 0 - is default value print(foo)- Count words in file with
getmethodname = input('Enter file:') handle = open(name) # print(name) foo_dict = dict() for line in handle: words = line.split() for word in words: foo_dict[word] = foo_dict.get(word,0) + 1 print(len(foo_dict))
Array
Cast data types
str()- to stringint()- if used on float it will round downfloat()-
Syntax
object.method
Function
def - define function
return - function’s return value. How function send result to fn. caller
- fn #(code inside fn must be indentet)
def foo(name, age): return name + ", you are " + agefoo("Adam", "30") # Hello Adam, you are 30
If, else, elif
Two branch if: - else:- statement
- Bool (logic):
-
foo = True bar = False if foo or bar: print("Foo or bar is True") else: print('Both are False')Compare:
def max_num(num1, num2, num3): if num1 >= num2 and num1 >= num3: return num1 elif num2 >= num1 and num2 >= num3: return num2 else: return num3
Try, Except / Input
Handle errors
try:
number = int(input("Enter a number: "))
print(number)
except:
print("Invalid Input")
- except detailed
try: value = 10/0 except ZeroDivisionError: print("Cannot divide by zero") except ValueError: print("Invalid Input") except: # can out as variable print("Except everything. This error is:" )
For Loop
- for each in string
for i in "bar": print(i) - for each in array
foo_array = ["B", "A", "R"] for i in foo_array: print(i)for i in range(len(foo_array)): - for index numbers
for index in range(5, 9): if index == 7: print('lucky 7') else: print(index) - Loop throu dictionary, using keys:
def foo_dict(): bar = {'a': 1, "b": 2,"c":3} for key in bar: vale = bar[key]
While Loop
i = 6
while i <= 9:
print(i)
i = i+1
# print 6, 7, 8, 9
Class
Class can mutate states of data inside / variable values Onject is instance of class.
- just an example Method
class Dog: def bark(self): print("bark") d = Dog() # assign var to instance of dog class # d is object of class dog print(type(d)) # <class `__main__.Dog`> d.bark() # can use method created in class.
__init__ - will be called whenever we call class (must fill criteria. )
self.name = name - (attr of class dog called name)then u need stoe somewhere
- simple class
class FooClass: foo_var = 'globalna zmienna' # class atribute def __init__(self, foo, bar, num): # initailize function to map attribs self.foo = foo # assign value foo to actual self.foo self.bar = bar # self is refering to actual object self.num = num def is_foo(self): # define fn inside of class if self.num >= 1: return True else: return Falsevalue1 = FooClass("Foo Velue 1", "Bar Value 1", 1) value2 = FooClass("Foo Velue 2", "Bar Value 2", 2) print(value1.foo) # call class value print(value1.is_foo()) # call class function - Inherent class
class BarClass(FooClass)
Inheretance
Inherent functionality, can override.
from a import a
class sub_category_of_a(a): # in sub_category_of_a can use all fn from a
Inheretacne
Modules / Libraries
can store vars and fn in files
Import Library
- External modules are in folder we instaled a python
external libraries/Lib/... - Instal external modules
import library
from math import *
External script files
- Run only if its used as scrpit, not when use as library (ie. during importing):
Should be in scripts meant to be runned:
def main(): print("Foobra") if __name__ == `__main__`: # run vs imported main()
NumPy
- better to use numpy or dedicated libraries written in c (faster)
def sum_range(n=100_000_000): return sum(range(n)) # # # faster from numpy import * def sum_numpy(n=100_000_000): return numpy.sum(numpy.arange(n))
pip
should be instaled
pip install
Strings
-
immutability (not mutable)
- fString:
print(f"Hello, {foo("fn")} ! {bar + 2} Have a nice day.") # f string -
\n- Next line - String to list
foo_string = `how,are,you,doing` foo_list = foo_string.split(',') # String to List foo_string = ''.join(foo_list) # List to String - Edit fn
# "StRiNg To LoW CaSe".lower() # Belong to strings, only attached to strings foo_string.upper() # foo_string.strip() # foo_string.replace("foo", "bar") # replace - Search fn
print(foo[3] + " - is 4-th letter of string") # search array for print(foo.index("ing")) # search array for in find('lo') startswith() # True / False endwith() # True / False - Find and repleace
foo_string = 'find this: barA and repleace with barB' foo_string.find('barA') foo_string.replace('barA', 'barB') # print('barB' in foo) # is barB in foo # (True) print('barC' in foo) # is barC in foo # (False) - xx
if 'A B' in foo_string print('yes')
Files
open() - return a file handle, so u can read a file. Arg: a - append / w - write / r - read / r+ - read write
close() - close every time you open or use context manager.
- Open, Close, Read
file = open('file.txt', 'r') foo = file.read()) file.close() # close everytime you open
Read
- Read
file = open("file.txt", "r")
print("Opened file info: " + str(file)
print("Is file readable: " + str(file.readable()))
print("Read lines in file:" + str(file.readline()))
file = open('file.txt', 'r')
for file in file.readlines():
print(file)
- use
withinstead of close whitch can be not closet in cas of exception.def foo(filename): with open(filename) as f: f.write("Hello!/n")
Copy
- Copy
import shutil shutil.copyfile("/path/filre1.ext", "/path/file2.ext") / LINUX/MAC shutil.copyfile("C:\path\file1.ext", "C:\path\file2.ext") / WIN
Write
- Permament append (simple version)
file = open('file.txt', 'a') file.write('\nNew line appended from python') # '\n' - create new line file.close()Override
Create new file
can use w to create file
JSON
| python | json |
|---|---|
| dict | object |
| list tupple | array |
| int long float | number |
| True, False | true false |
| None | null |
import json
- dict convert to jason. (Encoding / serialisation)
foo_dict = {'name': 'A', 'age': 20, 'city': New York } foo_json = json.dumps(foo_dict) # dumpS - for stringjson.dumps(foo_dict, indent=4, separators(';','=')) - read from file
with open('foo.json', 'r/w???') as file: json.dump(foo, file, indent=4) - Deserialization. Json file ! to dict
with open('foo.json', 'r') as file: foo_dict = json.load(file) - Deserialization. Json string ! to dict
foo_dict = json.loads(foo_json) - USTOM ENCODING FN!
def encode_usere(o): if isinstance(o, User): return{'name':o.name, 'age': o.age, o.__class__.__name__: True} else: raise TyperError('object of type uuser is not JSNO serializable') # userJSON = json.dumps(user, default=encode_user) print(userJSON) - USTOM ENCODING FN! https://youtu.be/HGOBQPFzWKo?t=10560
from json import JSONEncoder class UserEncoder(JSONEncoder): # def default(self,o): if isinstance(o, User): return{'name':o.name, 'age': o.age, o.__class__.__name__: True} resturn JSONEncoder.default(self,o) # userJSON = json.dumps(user, default=encode_user) print(userJSON)
Random
Snippets
Quiz
# class
class Question:
def __init__(self, prompt, answer):
self.prompt = prompt
self.answer = answer
# list of questions
question_prompt = [
'Q1 ? \n1. A\n2. B\n3. C\n\n',
'Q2 ? \n1. X\n2. Y\n3. Z\n\n',
'Q3 ? \n1. K\n2. L\n3. M\n\n'
]
# answers
questions = [
Question(question_prompt[0], 'a'),
Question(question_prompt[1], 'b'),
Question(question_prompt[2], 'c')
]
def run_test(questions):
score = 0 # new variable
for question in questions:
answer = input(question.prompt)
if answer == question.answer:
score += 1
print("Your score is:" + str(score) + '/' + str(len(questions)))
run_test(questions)
Sort tuples
Sort dict
foo_dict_sorted = sorted(foo_dict.items(), key=operator.itemgetter(1),reverse=True)
foo_dict_sorted = sorted(foo_dict.items())
for k, v in sorted(foo_dict.items()):
print(k,v)
List comprehension !!!!
Sort Dict by Value (instead of key)
- list of reversed tuples and then sort it (Construct list of tuples (value,key). get list otuples from dic. sort list of tuples > sort dict)
print(sorted([(k,v) for k,v in foo_.items()]))
https://youtu.be/8DvywoWv6fI?list=PLWKjhJtqVAbnqBxcdjVGgT3uVR10bzTEB&t=20241