Python For Quantum Mechanics#
Week 2: Cheatsheet#
2.1 Flow Control#
If Statments
Documentation: https://docs.python.org/3/tutorial/controlflow.html
if Condition==True: Execute this block elif Other_Condition==True: Execute this block elif Other_Condition==True: Execute this block . . . elif Other_Condition==True: Execute this block else: Execute this block
Try and Except
Documentation: https://docs.python.org/3/tutorial/errors.html
try: Block except: Block finally: Block
While Loops
While condition==True: Execute This Block
Range and Zip
range(start,stop,step)
Documentation: https://docs.python.org/3/library/functions.html#zip
zip(a,b)
For Loops
for i in (iterable object): Execute This Block
enumerate(a)
Break, Continue, Pass
Documentation: https://docs.python.org/3/tutorial/controlflow.html#break-and-continue-statements-and-else-clauses-on-loops
break #stops loops action continue #moves to the next iteration in the loop pass #moves onto the rest of the code block and following iterations
2.2 Compact Code#
One-Line If and Else
Documentation: https://www.codegrepper.com/code-examples/python/python+single+line+for+loop+with+if+else
x = one_thing if condtion else another_thing
Comprehensions
L = [x for x in (Iterable Object) if condition == True]
Documentation: https://docs.python.org/3/tutorial/datastructures.html#sets
S = {x for x in (Iterable Object) if condition == True}
D = {key:value for key,value in Dict.items() if condition == True}
Generators
G = (x for x in (Iterable Object) if condition == True)
2.3 External Data#
User Input
Documentation: https://docs.python.org/3/library/functions.html#input
input('Prompt here: ')
Reading from File
with open("file",'r') as f: f.read() #Reads entire file f.read(10) #Reads 10 characters f.readline() #Reads line f.readline() #Reads next line
Writing to File
with open("file",'a') as f: # or 'w' f.write("appends('a')/overwrites('w')")