python

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
=> {}

Basic Structures and Constructs

  • If the __name__ variable is set to __main__ the module is being loaded as a main script and 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

Loops/Iteration

colors = ["red", "green", "blue"]
 
for c in colors:
    print("%s" % c)
for k, v in dict.items():
    print(v)
for k in dict.keys():
    print(k + "\n")
for v in dict.values():
    print(v + "\n")
a = ["a", "b", "c"]
 
for k, v in enumerate(a):
 
    print("%s, %s\n" % (k,v))

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>

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

Resources/References

  • python.txt
  • Last modified: 2023/03/20 17:33
  • by mgupton