Add boolean check to a class
class AClass:
def \_\_init\_\_(self):
self.data = []
def \_\_bool\_\_(self):
return True if self.data else FalseChoose a random character from a string
item = random.choice(string)
Fastest check if something is ‘in’ for loop
for _ in range(0, 1000000):
b = m in {Moves.North, Moves.South, Moves.West, Moves.East} # slowest
b = m == Moves.North or m == Moves.South or m == Moves.West or m == Moves.East # slow
b = m in {Moves.North, Moves.South, Moves.West, Moves.East} # fastestExit codes
import sys sys.exit(0) # success sys.exit(1) # failure
Force the output buffer
import sys
for i in range(5):
print(i, end=' ')
sys.stdout.flush() # Forces the buffer to flush
time.sleep(1)How to prevent nesting?
Use guard clauses to invert ‘if’
if not data:
return "No data provided"