Skip to content

Instantly share code, notes, and snippets.

@edenau
edenau / break.py
Last active January 19, 2020 02:14
for a in range(5):
if a == 2:
break
print(a)
print('Final a is',a)
# 0
# 1
# Final a is 2
for a in range(5):
if a == 2:
continue
print(a)
# 0
# 1
# 3
# 4
import copy
a = [[0,1],[2,3]]
b = copy.copy(a)
print(id(a)==id(b))
# False
b[1] = 100
print(a,b)
a = [[0,1],[2,3]]
b = a
b[1][1] = 100
print(a,b)
# [[0, 1], [2, 100]] [[0, 1], [2, 100]]
print(id(a)==id(b))
# True
a = 1 # a variable
def increment():
a += 1
return a
def increment2():
global a # can make changes to global variable "a"
a += 1
return a
@edenau
edenau / monopoly-fun-fact.py
Created January 5, 2020 01:30
Chance of ending up in Jail after your first turn of Monopoly
# probability of getting imprisoned (not just visiting) in your first turn of a game
n_game = 1e6
n_round = 1
player = Player()
imprisoned_cnt = 0
board = Board()
for i in range(n_game): # simulate 10,000 games
player.new_game()
board.turn(player=player) # simulate a turn for each player
@edenau
edenau / monopoly-sim.py
Created January 5, 2020 01:23
Main script of Monte Carlo simulation of Monopoly
opponents = []
n_oppo = 4-1 # a 4-player game has 3 opponents
n_game = 1e6
n_round_mean, n_round_std = get_n_round_stat(n_oppo)
# 1. Create opponents in a list
for _ in range(n_oppo):
opponents.append(Player())
for i in range(2):
try:
print(i)
finally:
print('A sentence.')
continue
print('This never shows.')
# Python <= 3.7
>> SyntaxError: 'continue' not supported inside 'finally' clause
pi = 3 # I studied Engineering
print(f'π equals {pi}.') # π equals 3.
print(f'{pi=}') # pi=3
# take it or leave it
a = 6
# The following statement
# assigns the value a ** 2 to variable b,
# and then check if b > 0 is true
if (b := a ** 2) > 0:
print(f'The square of {a} is {b}.') # The square of 6 is 36.