60 likes | 199 Views
Tips. Iteration. On a list: group = [" Paul","Duncan","Jessica "] for person in group : print( group ) On a dictionary : stock = {'eggs':15, 'milk':3, 'sugar':28} Iterate over keys : for ingredient in stock.iterkeys (): Iterate over values :
E N D
Iteration • On a list: • group = ["Paul","Duncan","Jessica"]for person in group: print(group) • On a dictionary: • stock = {'eggs':15, 'milk':3, 'sugar':28} • Iterate over keys: • for ingredient in stock.iterkeys(): • Iterate over values: • for count in stock.itervalues(): • Iterate over both: • for ingredient,count in stock.iteritems()
Workingdirectory • The Python sessions workingdirectory is set as the directory from wherePython is called. • This alsoapplieswhen, in Windows, youedit a file in IDLE. • In Windows, the "Start in"-property of a shortcutdetermines the workingdirectory. If it is empty, the directorywhere the shortcut is placed is used. • To change the workingdirectory from withinPython: • import osos.getcwd() # getcurrentworkingdirectoryos.chdir(path) # changeworkingdirectory
Executing a script file • To execute a script file, from a consolewrite: • python scriptfile.py • (This requires the pythondirectory is in the PATH environment variable.) • It is possible to pass arguments to the script: • python script arg1 arg2 • In the script file, the arguments canbefound in the variable sys.argv(remember to import sys).
Executing a script file • To differentiate a script from being run as a module or as a independent script, do as below: • if __name__ == '__main__': # Suite to beexecutedwhen script # is calledindependentantly. • Code outside the if-blocks suite, is alwaysexecuted.