python

This is an old revision of the document!


Python

Core Elements & Constructs

l = []
 
l.append("alpha")
l.append("beta")
 
for e in l:
  print(e)
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
=> {}
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 be testing whether or not a identifier is defined or not. </WRAP>

x_exists = 'x' in locals() or 'x' in globals()
try:
  x
except NameError:
  x_exists = False
else:
  x_exists = True
hasattr(a, 'property')
if args.file is None or len(args.file) == 0:
 
    pass
  • python.1493067169.txt.gz
  • Last modified: 2017/04/24 20:52
  • by mgupton