This is an old revision of the document!
Python
Core Elements & Constructs
Lists
l = [] l.append("alpha") l.append("beta") for e in l: print(e)
Dictionaries
d = {'alpha': 'plucky', 'beta': 'scrappy'} print(d['alpha']) print(d.get('alpha')) del d['alpha'] # Remove all elements. d.clear() d['gamma'] = 'spunky' # Delete the dictionary itself. del d
b={} => None b["alpha"] = 10 => None b => {'alpha': 10} del b["alpha"] => None b => {}
Iterate over keys and values of dictionary
for k, v in dict.items(): print(v)
for k in dict.keys(): print(k + "\n")
for v in dict.values(): print(v + "\n")
Basic Structures and Constructs
- If the __name__ variable is set to __main__ the module is being loaded as a program entry point. Otherwise it's being loaded as a library module.
if __name__ == "__main__": print("Hello World.") else: pass
Conditionals
num = 100 a = ["alpha", "beta", "gamma"] if "beta" in a: pass if num > 10: pass elif num < 10: pass else: pass
Common Elements and Ways
Determine if variable is defined
<WRAP round info> It might be a code smell/anti-pattern to test whether or not an identifier is defined. That is, testing whether a variable is defined considered harmful. </WRAP>
Method 1
x_exists = 'x' in locals() or 'x' in globals()
Method 2
try: x except NameError: x_exists = False else: x_exists = True
Method 3
hasattr(a, 'property')
Method 4
if args.file is None or len(args.file) == 0: pass