forked from ernestas-poskus/interactive-programming-python
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcode_tips6.py
More file actions
100 lines (65 loc) · 1.33 KB
/
code_tips6.py
File metadata and controls
100 lines (65 loc) · 1.33 KB
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
###################
# Broken code
class Ball:
def __init__(self, pos, rad):
self.position = pos
self.radius = rad
def get_position(self):
return self.position
b = Ball([0,0], 10)
print b.get_position()
###################
# Fixed code
class Ball:
def __init__(self, pos, rad):
self.position = pos
self.radius = rad
def get_position(self):
return self.position
b = Ball([0,0], 10)
print b.get_position()
##################
# Mutation with classes and objects
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def set_x(self, newx):
self.x = newx
def get_x(self):
return self.x
p = Point(4, 5)
q = Point(4, 5)
r = p
p.set_x(10)
print p.get_x()
print q.get_x()
print r.get_x()
##################
# Example while
def countdown(n):
"""Print the values from n to 0."""
i = n
while i >= 0:
print i
i -= 1
countdown(5)
##################
# Collatz
def collatz(n):
"""Prints the values in the Collatz sequence for n."""
i = n
while i > 1:
print i
if i % 2 == 0:
i = i / 2
else:
i = 3 * i + 1
collatz(1000)
#################
# Timeout
i = 1
while i <= 10:
i += 1
print i
print "Done!"