-
Notifications
You must be signed in to change notification settings - Fork 214
/
Copy pathfor_else.py
163 lines (129 loc) · 3.6 KB
/
for_else.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
import random
import time
import pytest
def basic_syntax_for():
for x in range(3):
if x == 2:
break
print(x)
else:
print("DONE")
def basic_syntax_while():
x = 0
while x < 3:
if x == 2:
break
print(x)
x += 1
else:
print("DONE")
def the_intuition():
x = 0
# START
if x < 3:
... # a break would GOTO END
x += 1
# GOTO START
else: # no break
print("while terminated without break or exception")
# END
def index_foundflag(seq, target):
found = False
for idx, val in enumerate(seq):
if val == target:
found = True
break
if not found:
raise ValueError(f'{target} is not in the sequence')
return idx
def index_forelse(seq, target):
for idx, val in enumerate(seq):
if val == target:
break
else: # no break
raise ValueError(f'{target} is not in the sequence')
return idx
def index_return(seq, target):
for idx, val in enumerate(seq):
if val == target:
return idx
raise ValueError(f'{target} is not in the sequence')
def countdown_flag(groups, ticks_per_group):
ticks = [ticks_per_group - 1] * groups
yield tuple(ticks)
keep_going = True
while keep_going:
keep_going = False
for group in reversed(range(groups)):
if ticks[group] != 0: # can subtract 1 from this group
ticks[group] -= 1
yield tuple(ticks)
keep_going = True
break
ticks[group] = ticks_per_group - 1 # reset
def countdown_forelse(groups, ticks_per_group):
ticks = [ticks_per_group - 1] * groups
yield tuple(ticks)
while True:
for group in reversed(range(groups)):
if ticks[group] != 0: # can subtract 1 from this group
ticks[group] -= 1
yield tuple(ticks)
break
ticks[group] = ticks_per_group - 1 # reset
else:
return
def random_error():
return random.random() > .9
def process_for_5_seconds_errorflag():
random.seed(4)
start = time.perf_counter()
target_time = start + 5
errored = False
while (now := time.perf_counter()) < target_time:
print(f"keep working, it's only been {now - start:.2f}s")
if random_error():
errored = True
break
time.sleep(.5)
if errored:
print("handling error...")
else:
print("done!")
def process_for_5_seconds_whileelse():
random.seed(4)
start = time.perf_counter()
target_time = start + 5
while (now := time.perf_counter()) < target_time:
print(f"keep working, it's only been {now - start:.2f}s")
if random_error():
break
time.sleep(.5)
else: # no break
print("done!")
return
print("handling error...")
def not_all_elses_are_bad(x, y):
try:
z = x / y
...
except ZeroDivisionError:
# was it the x / y that raised?
# or something in the ...?
return float('nan')
try:
z = x / y
except ZeroDivisionError:
return float('nan')
else:
... # safe to use z
def main():
assert index_forelse([0, 1, 2, 3], 0) == 0
assert index_forelse([3, 2, 1, 0], 0) == 3
assert index_forelse([3, 1, 0, 2], 0) == 2
with pytest.raises(ValueError):
index_forelse([0, 1, 2, 3], 5)
# better to use builtin .index of list
assert [0, 1, 2, 3].index(0) == 0
if __name__ == '__main__':
main()