# Python Idle on Linux # Python Idle on Linux # sudo apt-get install idle3 e.ggtimer.com # import module with pip python -m pip install timedelta python -m pip install jwt pip install pyjwt # Python 3.0.0 and higher must have proper syntax, see below print ("This is a string") print "This is a string" a = 100 print "a = ",a ===================================================== # print vypis # print value using curly brackets ip = "8.8.8.8" print(f"UP {ip} -Ping OK") # UP 8.8.8.8 -Ping to internet succesful ===================================================== #################################################################################### # toto je koment #################################################################################### # initialization a = 3 b = 7 # or a,b = 3,7 # finta zapisu jedneho riadku a,b = 1,1 1) a, b = b, a + b # a=1, b=2 (neberie sa sucasne zmenena hodnota a) 2) a, b = b, a + b # a=2, b=3 3) a, b = b, a + b # a=3, b=5 -sanka_dole_sefe- # bez zapisu v jednom riadku a,b = 1,1 1) a = b # a=1 b = a + b # b=2 2) a = b # a=2 b = a + b # b=4 3) a = b # a=4 b = a + b # b=8 -kua- ############################################### # PRINT, Vypis Print print("Ahoj") # PRINT in one line txt = "For only {price:.2f} dollars!" print(txt.format(price = 49)) # For only 49.00 dollars! # pole = ["Mika", "Luka", "Fufucka", "Ajo"] for index,x in enumerate(pole): txt = str(index) + " {}" + ", " print(txt.format(x), end="") # 0 Mika, 1 Luka, 2 Fufucka, 3 Ajo, ############################################### ############################################### ############################################### # TUPLE (is immutable - nemenny) tuple1 = (1,2,3) tuple2 = ("A", 0, True, "something") a = (1,2,3,4,5,6,7,8,9,10) print(a[2::]) # (3, 4, 5, 6, 7, 8, 9, 10) #Python has two built-in methods that you can use on tuples. #count() Returns the number of times a specified value occurs in a tuple #index() Searches the tuple for a specified value and returns the position of where it was found # tuple count() tuple1 = ('Apple', True, 0, 17, 'Ajo', 'Apple') tuple1.count(0) # 1 tuple1.count("Apple") # 2 # tuple index() tuple1 = ('Apple', True, 0, 17, 'Ajo', 'Apple') tuple1.index("Ajo") # 4 tuple1.index("Apple") # 0 #SRANDA, SI TAM AZ DVE A ON UKAZE IBA PRVU :-) # LIST, Novy prazdny zoznam zoznam = list() print(type(zoznam)) # print(len(zoznam)) # 0 # priamo bez klucoveho slova "list" zoznam2 = [1,4,6,8,5,8,0] d = [1,2,3,4,5,"a"] # list with different types of elements # List Methods: append() Adds an element at the end of the list clear() Removes all the elements from the list copy() Returns a copy of the list count() Returns the number of elements with the specified value extend() Add the elements of a list (or any iterable), to the end of the current list index() Returns the index of the first element with the specified value insert() Adds an element at the specified position insert(, ) pop() Removes the element at the specified position pop() remove() Removes the first item with the specified value remove() reverse() Reverses the order of the list sort() Sorts the list sort(reverse, key) Sorts the list # clear the list zoznam2 = [1,4,6,8,5,8,0] zoznam2.clear() print(zoznam2) # [] # copy list fruits = ['apple', 'banana', 'cherry', 'orange'] fruits2 = fruits print(fruits2) # ['apple', 'banana', 'cherry', 'orange'] fruits3 = fruits.copy() print(fruits3) # ['apple', 'banana', 'cherry', 'orange'] # count items in list fruits = ["apple", "banana", "cherry", "apple"] fruits.count("apple") # 2 x = fruits.count("cherry") print(x) # 1 # extend list fruits = ['apple', 'banana', 'cherry'] cars = ['Ford', 'BMW', 'Volvo'] fruits.extend(cars) print(fruits) # ['apple', 'banana', 'cherry', 'Ford', 'BMW', 'Volvo'] # index of item in the list fruits = ['apple', 'banana', 'cherry'] x = fruits.index("cherry") print(x) # 2 # insert() takes exactly 2 arguments insert() Adds an element at the specified position pole = ["Ajo", "Fufu", "Mika", "Luka"] pole.insert(2,"Havko") # ['Ajo', 'Fufu', 'Havko', 'Mika', 'Luka'] # pop() Removes the element at the specified position pole # ['Ajo', 'Fufu', 'Havko', 'Mika', 'Luka'] pole.pop() # ['Ajo', 'Fufu', 'Havko', 'Mika'] pole.pop(3) # ['Ajo', 'Fufu', 'Havko'] a = pole.pop(0) # a = "Ajo" # remove() takes exactly one argument remove() Removes the first item with the specified value pole # ['Ajo', 'Fufu', 'Luka', 'Mika', 'Havko'] pole.remove("Fufu") # ['Ajo', 'Luka', 'Mika', 'Havko'] ############################################### # APPEND, Pridanie do zoznamu zoznam = ["Andrej"] a = "Mazak" zoznam.append(a) # pridanie na koniec zoznamu print(len(zoznam)) # 2 print(zoznam) # ['Andrej', 'Mazak'] ????? PRIDANIE NA PRESNU POZICIU ???? ############################################### # REVERSE, Obratit Otocit zoznam zoznam = list() zoznam.append("Andrej") zoznam.append("Mazak") print(zoznam) # ['Andrej', 'Mazak'] zoznam.reverse() print(zoznam) # ['Mazak', 'Andrej'] # The reverse() method doesn't take any arguments. systems = ['Windows', 'macOS', 'Linux'] # Syntax: reversed_list = systems[start:stop:step] reversed_list = systems[::-1] # ['Linux', 'macOS', 'Windows'] # works same way for tuple too a = (1,2,3,4,5,6,7,8,9,10) # tuple print(a[::-1]) # (10, 9, 8, 7, 6, 5, 4, 3, 2, 1) print(a[::-2]) # (10, 8, 6, 4, 2) # by for loop with "reversed" key word systems = ['Windows', 'macOS', 'Linux'] # list sastems = ('Windows', True, 16) # Tuple for o in reversed(systems): print(o) Linux macOS Windows # works same way for tuple too ############################################### # SORT, Zotriedit zoznam - vsetky prvky MUSIA BYT rovnake https://www.programiz.com/python-programming/methods/list/sort # # By default, sort() doesn't require any extra parameters. # However, it has two optional parameters: # "reverse" - If True, the sorted list is reversed (or sorted in Descending order) # "key" - function that serves as a key for the sort comparison # The sort() method doesn't return any value. Rather, it changes the original list # If you want a function to return the sorted list, use sorted() # zoznam = list() zoznam.append("Andrej") zoznam.append("Zuzana") zoznam.append("Lucka") zoznam.append("Miska") print(zoznam) # ['Andrej', 'Zuzana', 'Lucka', 'Miska'] zoznam.sort() print(zoznam) # ['Andrej', 'Lucka', 'Miska', 'Zuzana'] # zoznam2 = list() zoznam2 = [1,4,6,8,5,8,0] print(zoznam2) # [1, 4, 6, 8, 5, 8, 0] zoznam2.sort() print(zoznam2) # [0, 1, 4, 5, 6, 8, 8] # list1 = [3,5,7,8,5,3,11,0] list1.sort(reverse=True) print(list1) # [11, 8, 7, 5, 5, 3, 3, 0] # list2 = sorted(list1, reverse=True) print(list2) # [11, 8, 7, 5, 5, 3, 3, 0] # list3 = ["Andrej", "Mika", "Lucka", "Fufu"] list3.sort(key=len) print(list3) # ['Mika', 'Fufu', 'Lucka', 'Andrej'] # employees = [ { 'Name': 'Alan Turing', 'age': 25, 'salary': 10000 }, { 'Name': 'Sharon Lin', 'age': 30, 'salary': 8000 }, { 'Name': 'John Hopkins', 'age': 18, 'salary': 1000 }, { 'Name': 'Mikhail Tal', 'age': 40, 'salary': 15000 } ] def get_name(employee): return employee.get('Name') employees.sort(key=get_name) print(employees, end='\n\n') # [ {'Name': 'Alan Turing', 'age': 25, 'salary': 10000}, {'Name': 'John Hopkins', 'age': 18, 'salary': 1000}, {'Name': 'Mikhail Tal', 'age': 40, 'salary': 15000}, {'Name': 'Sharon Lin', 'age': 30, 'salary': 8000} ] # ############################################### # Vypis prvku v Zozname zoznam3 = list() zoznam3 = ["Andrej", "Mazak", 1, 216, "Lincoln", 0] print(zoznam3) # ['Andrej', 'Mazak', 1, 216, 'Lincoln', 0] print(zoznam3[:]) # ['Andrej', 'Mazak', 1, 216, 'Lincoln', 0] - TO ISTE print(zoznam3[2:]) # [1, 216, 'Lincoln', 0] print(zoznam3[-1]) # 0 print(zoznam3[1:3]) # ['Mazak', 1] # check if item is list if isinstance(item, list): ############################################### # Spajanie Zoznamov zoznam1 = ['Andrej', 'Zuzana', 'Lucka', 'Miska'] zoznam2 = [1, 4, 6] zoznam3 = zoznam1 + zoznam2 print(zoznam3) # ['Andrej', 'Zuzana', 'Lucka', 'Miska', 1, 4, 6] ############################################### # Najdi Poziciu v Zozname zoznam1 = ['Andrej', 'Zuzana', 'Lucka', 'Miska'] print(zoznam1.index("Lucka")) # 2 ############################################### # Vymaz Polozku v Zozname zoznam1 = ['Andrej', 'Zuzana', 'Lucka', 'Miska'] del zoznam1[0] print(zoznam1) # ['Zuzana', 'Lucka', 'Miska'] # zoznam2 = ['Andrej', 'Zuzana', 'Lucka', 'Miska', 1, 4, 6] del zoznam2[2:] print(zoznam2) # ['Andrej', 'Zuzana'] # delete selected items from list lis = [2, 1, 3, 5, 4, 3, 8] del lis[2 : 5] # [2, 1, 3, 8] ############################################### # vypis dva zoznamy naraz a = [1, 2, 3, 4] b = ["x", "y", "z"] for i in (a+b): print(type(i), i) # 1 2 3 4 x y z # ############################################### # Najdi najdlhsi string v zozname >>> mylist = ['123','123456','1234'] >>> print max(mylist, key=len) 123456 # Najdi najaktualnejsi (latest) string v zozname highest_FW_file = max(all_found_fw_files) ############################################### # Najdi string v zozname, ktory ma najvecsiu hodnotu >>> c = ["g3100_1.3.6", "g3100_1.5.0", "g3100_1.4.7"] >>> print(max(c)) g3100_1.5.0 ############################################### # RANGE, Vytvorenie zoznamu s cislami vzostupne zoznam4 = list(range(3)) print(zoznam4) # [0, 1, 2] # zoznam5 = list(range(1,10)) print(zoznam5) # [1, 2, 3, 4, 5, 6, 7, 8, 9] ############################################### # Zoznam Zoznamov zoznam6 = ["Pondelok", ["bageta", "maslo", "dzem"], "Utorok", ["rozok", "syr", "sunka"], "Streda", ["mlieko"]] print(len(zoznam6)) # 6 print(zoznam6[3]) # ['rozok', 'syr', 'sunka'] print(zoznam6[3][0]) # rozok ############################################### # pondelok = ["matematika", "fyzika", "pocitace"] utorok = pondelok utorok.append("hudobna") print(pondelok) ############################################### # Move element to end of the list test_list = ['3', '5', '7', '9', '11'] # ['3', '5', '7', '9', '11'] test_list.append(test_list.pop(test_list.index("5"))) # ['3', '7', '9', '11', '5'] ############################################### # Print list in one line a = ["jeden", "dva", "tri"] for i in a: print(i, end=" ") # jeden dva tri #in Python3 print(*a) # jeden dva tri #or print (" ".join(str(x) for x in a)) # jeden dva tri ############################################### # join list of strings a = ['3', '1', '0', '1'] b = (".".join(a)) # 3.1.0.1 ############################################### # STRINGS print a single letter or letters retazec = "Andrej" print(retazec[1]) # n print(retazec[1:]) # ndrej print(retazec[2:]) # drej print(retazec[-1:]) # j print(retazec[-1]) # j print(retazec[-2:]) # ej print(retazec[-2]) # e print(retazec[-3]) # r print(retazec[:-3]) # And print(retazec[:-1]) # Andre print(retazec[:4]) # Andr # -6 -5 -4 -3 -2 -1 # A n d r e j # 0 1 2 3 4 5 ############################# # add character into string a = "04a222c8f3b9" a = a[:2] + ":" + a[2:] # '04:a222c8f3b9' # a = "04a222c8f3b9" a = a[:2] + ":" + a[2:4] + ":" + a[4:6] + ":" + a[6:8] + ":" + a[8:10] + ":" + a[10:12] # '04:a2:22:c8:f3:b9' ############################# # split string at position str = "hello world!" splitat = 4 l, r = str[:splitat], str[splitat:] #hell #o world! ############################################### # Print last line of String print (response.splitlines()[response.count('\n')]) ############################################### # if not in if zoznam not in zoznamAll: ... ############################################### # FOR simple for - slucka for x in zoznamAll: print(x) ############################################### # FOR range 1 to 10 for i in range(10): print(i) # 0 1 2 3 4 5 6 7 8 9 # for i in range(3, 6): print(i) # 3 4 5 # od 4 do 10 krokovat po dvoch for i in range(4, 10, 2): # 4 6 8 print(i) # od 0 do -10 krokovat po minusDva for i in range(0, -10, -2): print(i) # 0 -2 -4 -6 -8 # my_list = ['one', 'two', 'three', 'four', 'five'] my_list_len = len(my_list) for i in range(0, my_list_len): print(my_list[i]) # one two three four five # traverse two lists list1 = [1,2,3,4,5] list2 = ["a", "b", "c", "d", "e"] for i,j in zip(list1,list2): print(i, " ", j) #1 a #2 b #3 c #4 d #5 e ############################################### # Otvorenie suboru a citanie ho po riadkoch, FILE with open('rmv.html') as f: lines = f.readlines() # Otvorenie suboru a citanie ho po riadkoch - bez EOL with open('tickers.txt') as t: all_tickers_with_eol = t.readlines() all_tickers = [line[:-1] for line in all_tickers_with_eol] # ['AAPL', 'SOLO', ...] ############################################### # subor f = open("ajo.txt", "w") f.write("Andrej") f.write("Mazak") f.close() ################################################### # read file without end of lines input_file = open("us_cities.txt",'r') job_location = input_file.read().splitlines() # read file end of liens ############################################### # Prazdny retazec rozdelovnik = "" ############################################### # Vypis uvodzovky print("\"") print("\"") # Vypis lomitko print("\\") ############################################### # Slucka FOR, rozdelenie riadku podla stringu for x in lines: print(x) a = x.split("mailto:")[1] ############################################### # Slucka WHILE while (i< (len(b)/2)): print("Helou") ############################################### # Skrateny vypis retazca print(b[:1]) ############################################### # sleep pauza - po sekunde from time import sleep sleep(1) ############################################### # argument import os,sys os.path.basename(sys.argv[0]) print(sys.argv[0]) # hramSa.py print(sys.argv[1]) # vytlaci moj prvy argument "ahoj" - pokial som spustal "python hramSa.py ahoj" try: a = sys.argv[1] except: # run cli command import os os.system("dir") # Manually raise exception raise Exception('I know Python!') ############################################### # argument fileName = sys.argv[0] ############################################### # try + except try: pocetPrikladov = sys.argv[1] except IndexError: pocetPrikladov = 40 ############################################### # check file size import os statinfo = os.stat('ahoj.txt') print(statinfo) print(statinfo.st_size) ############################################### # cas v slucke (nastavenie trvania slucky) import time t_end = time.time() + 60 * float(durationMinutes) while time.time() < t_end: # pokrac ############################################### # zobrazenie okamziteho casu import time import datetime start_time = time.time() print(datetime.datetime.utcfromtimestamp(time.time() - start_time).strftime('%H:%M:%S')) ############################################### # FTP download import ftplib ftp = ftplib.FTP("68.128.154.246") ftp.login("testuser1", "ubuntu") filematch = '*.dum' for filename in ftp.nlst(filematch): fhandle = open(filename, 'wb') print('Getting ' + filename) ftp.retrbinary('RETR '+ filename, fhandle.write) fhandle.close() ftp.quit() ############################################### ############################################### ############################################### # OS. # aktualny adresar actualDir = os.getcwd() print(actualDir) # c:\Python37\To-BE-DELETED_JSON_Parser_2 # vypis cestu k suboru import os, sys a = os.getcwd() + "\\" + "wpa_supplicant.conf" print(a) # c:\Python37\BHRx_Change_SSID_raspi4\wpa_supplicant.conf # file size import os file_size = os.getcwd() + "\\NEWS.txt" # integer number, 632203 # obsah adresara (bez pod-adresarov) directoryContent = os.listdir(os.getcwd()) print(directoryContent) # ['hramSa_02.py', 'JSON_schemas', 'parseJsonSchemas.py'] print(type(directoryContent)) # # Search for all the files inside currect folder from glob import glob for file in glob( "**", recursive = True ): if not os.path.isdir( file ): print(file) ############################################### # vymaz subor os.remove(fileName) ############################################### ############################################### ############################################### # input from console input_var = input("Enter a number: ") ############################################### # print new line print("\n") ############################################### # Replace ' with " retazec2 = retazec.replace("'", "\"") a = "1,500" b = a.replace(",","") print(b) # 1500 ############################################### # RANDOM STRING FOR FILE def id_generator(size=randint(10,20), chars=string.ascii_uppercase + string.digits): return ''.join(random.choice(chars) for _ in range(size)) randomStringForFileName = id_generator() ############################################### # random file - nahodne cislo od 0 do 10 from random import randint cislo1 = randint(0, 10) ############################################### # HTML a1 = "" a2 = "
" ############################################### # Object Orienting class LepsiTiskarna: # definice třídy s názvem LepsiTiskarna def nastavTisk (self, co): self.vytisk = co def tiskniTo (self): print (self.vytisk) class JesteLepsiTiskarna (LepsiTiskarna): def pridejTo (self, co): self.vytisk = self.vytisk + co class SZTiskarna (LepsiTiskarna): def __init__ (self, co): self.vytisk = co print ("Narodila se instance ze třídy SZTiskarna.") print ("Huráááááááá, jsem živá!") # Program: novyObjekt = LepsiTiskarna() novyObjekt.nastavTisk("Titulka") novyObjekt.tiskniTo() # Titulka print(novyObjekt.vytisk) # Titulka erazitko = JesteLepsiTiskarna() erazitko.nastavTisk ("zdravime pozemstany") erazitko.tiskniTo() # zdravime pozemstany erazitko.pridejTo (", zaved mne ke svemu vedoucimu.") erazitko.tiskniTo() # zdravime pozemstany, zaved mne ke svemu vedoucimu. mojeTiskarna = SZTiskarna ("Bonjour") # Narodila se instance ze trídy SZTiskarna. # Huráááááááá, jsem zivá! print(mojeTiskarna.vytisk) # Bonjour ############################################### https://stackoverflow.com/questions/576169/understanding-python-super-with-init-methods #Import to Excel https://stackoverflow.com/questions/13437727/writing-to-an-excel-spreadsheet # JSON and Dictionary # Python Dictionary Methods clear() Removes all the elements from the dictionary copy() Returns a copy of the dictionary fromkeys() Returns a dictionary with the specified keys and value dictionary.fromkeys(sequence[, value]) get() Returns the value of the specified key dictionary.get(keyname, ) items() Returns a "dict_items" list containing a tuple for each key value pair del[] Delete key value pair in the Dictionary keys() Returns a list containing of all the keys in the dictionary update() The update() method adds element(s) to the dictionary if the key is not in the dictionary. If the key is in the dictionary, it updates the key with the new value. values() Returns a list of all the values in the dictionary pop() Removes pair and returns value of element from a dictionary having the given key. popitem() Removes the last inserted key-value pair setdefault() Returns the value of the specified key. If the key does not exist: insert the key, with the specified value import json payload = { "iat": iat, "exp": exp } print(payload) # {'iat': 1578514837357, 'exp': 1578597637357} print(json.dumps(payload)) # {"iat": 1578514837357, "exp": 1578597637357} # get() # get() method takes maximum of two parameters: # key - key to be searched in the dictionary # value (optional) - Value to be returned if the key is not found. The default value is None. d1={'Name': 'Alan Turing', 'age': 25, 'salary': 10000} d1.get('Name') # 'Alan Turing' # # clear the dictionary d1.clear() print(d1) # {} # copy dictionary d1={'Name': 'Alan Turing', 'age': 25, 'salary': 10000} d2 = d1 # with "=" a new reference to the original dictionary is created d3 = d1.copy() d1.clear() print(d1) # {} print(d2) # {} print(d3) # {'Name': 'Alan Turing', 'age': 25, 'salary': 10000} # fromkeys() # fromkeys() method takes two parameters: # sequence - sequence of elements which is to be used as keys for the new dictionary # value (Optional) - value which is set to each each element of the dictionary # mutable dictionary x = ('key1', 'key2', 'key3') y = 0 thisdict = dict.fromkeys(x, y) # ['key1': 0, 'key2': 0, 'key3': 0] # x = ('key1', 'key2', 'key3') thisdict = dict.fromkeys(x) # ['key1': None, 'key2': None, 'key3': None] # keys = {'a', 'e', 'i', 'o', 'u' } value = [1] vowels = dict.fromkeys(keys, value) # {'e': [1], 'i': [1], 'o': [1], 'a': [1], 'u': [1]} value.append(2) print(vowels) # {'e': [1, 2], 'i': [1, 2], 'o': [1, 2], 'a': [1, 2], 'u': [1, 2]} value.clear() print(vowels) # {'e': [], 'i': [], 'o': [], 'a': [], 'u': []} # # imutable dictionary - dont use fromkeys() keys = {'a', 'e', 'i', 'o', 'u' } value = [1] vowels = { key : list(value) for key in keys } print(vowels) # {'a': [1], 'e': [1], 'u': [1], 'o': [1], 'i': [1]} value.append(2) # [1, 2] print(vowels) # {'a': [1], 'e': [1], 'u': [1], 'o': [1], 'i': [1]} # list1 = ["ajo", "fufu", "luka", "mika"] list2 = [42,38,11,8] slovnik = { key : value for key,value in zip(list1,list2) } # or slovnik = { i : j for i,j in zip(list1,list2) } print(slovnik) # {'ajo': 42, 'fufu': 38, 'luka': 11, 'mika': 8} # items() - doesn't take any parameters marks = {'Physics':67, 'Maths':87} print(marks.items()) # dict_items([('Physics', 67), ('Maths', 87)]) # for i in a: print(i, " ", type(i)) # ('Physics', 67) # ('Maths', 87) # del[marks["Physics"]] print(marks.items()) # dict_items([('Maths', 87)]) # keys() person = {'name': 'Phill', 'age': 22, 'salary': 3500.0} print(person.keys()) # dict_keys(['name', 'age', 'salary']) # person = {'name': 'Phill', 'age': 22, } keys = person.keys() print(keys) # dict_keys(['name', 'age']) person.update({'salary': 3500.0}) print(keys) # dict_keys(['name', 'age', 'salary']) # update() marks = {'Physics':67, 'Maths':87} internal_marks = {'Practical':48} marks.update(internal_marks) print(marks) # {'Physics': 67, 'Maths': 87, 'Practical': 48} # d = {1: "one", 2: "three"} d1 = {2: "two"} d.update(d1) print(d) # {1: 'one', 2: 'two'} !!!!!!!!!!!!!!!!!!!!!!!!! d1 = {3: "three"} d.update(d1) print(d) # {1: 'one', 2: 'two', 3: 'three'} # d = {'x': 2} d.update(y = 3, z = 0) print(d) # {'x': 2, 'y': 3, 'z': 0} d.update(enabled = True) print(d) # {'x': 2, 'y': 3, 'z': 0, 'enabled': True} # values() marks = {'Physics':67, 'Maths':87} marks.values() # dict_values([67, 87]) # sales = { 'apple': 2, 'orange': 3, 'grapes': 4 } values = sales.values() print(values) # dict_values([2, 3, 4]) del[sales['apple']] print(values) # dict_values([3, 4]) print(sales) # {'orange': 3, 'grapes': 4} # pop() # dictionary.pop(key[, default]) # default = value which is to be returned when the key is not in the dictionary https://www.programiz.com/python-programming/methods/dictionary/pop marks = { 'Physics': 67, 'Chemistry': 72, 'Math': 89 } element = marks.pop("Chemistry") print(marks) # {'Physics': 67, 'Math': 89} print(element) # 72 # sales = { 'apple': 2, 'orange': 3, 'grapes': 4 } print(sales) # {'apple': 2, 'orange': 3, 'grapes': 4} element = sales.pop('guava') # KeyError: 'guava' element = sales.pop('guava', 676) print(sales) # {'apple': 2, 'orange': 3, 'grapes': 4} print(element) # 676 ############################################## # Environment env variable # in windows cmd: set andrej=41 import os print(os.environ['andrej']) # python.exe del.txt # 41 # adding specific timestamp with date and instant time from datetime import datetime tmp = datetime.now().strftime("%d/%m/%Y %H:%M:%S").split(" ") specific_timestamp = tmp[0].replace("/","-") + "_" + tmp[1].replace(":","-") # Perf_output_26-05-2020_15-51-33.txt # Import Module from other folder Create an empty file "__init__.py" in subdirectory /lib. And add at the begin of main code from __future__ import absolute_import then from lib. import bt_function ... bt_function() # check versions of python modules pip freeze # enumerate l1 = ["eat","sleep","repeat"] for ele in enumerate(l1): print (ele) # (0, 'eat') # (1, 'sleep') # (2, 'repeat') # enumerate l1 = ["eat","sleep","repeat"] for count,ele in enumerate(l1,100): print (count,ele) # 100 eat # 101 sleep # 102 repeat # enumerate # ------------------------------------------------- # Python Linked List # Python Lambda functions # Python OverRide