Contact
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutSign UpSign In
| Download

📚 The CoCalc Library - books, templates and other resources

Views: 96168
License: OTHER
1
"""This module contains a code example related to
2
3
Think Python, 2nd Edition
4
by Allen Downey
5
http://thinkpython2.com
6
7
Copyright 2015 Allen Downey
8
9
License: http://creativecommons.org/licenses/by/4.0/
10
"""
11
12
from __future__ import print_function, division
13
14
15
class Point:
16
"""Represents a point in 2-D space.
17
18
attributes: x, y
19
"""
20
21
22
def print_point(p):
23
"""Print a Point object in human-readable format."""
24
print('(%g, %g)' % (p.x, p.y))
25
26
27
class Rectangle:
28
"""Represents a rectangle.
29
30
attributes: width, height, corner.
31
"""
32
33
34
def find_center(rect):
35
"""Returns a Point at the center of a Rectangle.
36
37
rect: Rectangle
38
39
returns: new Point
40
"""
41
p = Point()
42
p.x = rect.corner.x + rect.width/2.0
43
p.y = rect.corner.y + rect.height/2.0
44
return p
45
46
47
def grow_rectangle(rect, dwidth, dheight):
48
"""Modifies the Rectangle by adding to its width and height.
49
50
rect: Rectangle object.
51
dwidth: change in width (can be negative).
52
dheight: change in height (can be negative).
53
"""
54
rect.width += dwidth
55
rect.height += dheight
56
57
58
def main():
59
blank = Point()
60
blank.x = 3
61
blank.y = 4
62
print('blank', end=' ')
63
print_point(blank)
64
65
box = Rectangle()
66
box.width = 100.0
67
box.height = 200.0
68
box.corner = Point()
69
box.corner.x = 0.0
70
box.corner.y = 0.0
71
72
center = find_center(box)
73
print('center', end=' ')
74
print_point(center)
75
76
print(box.width)
77
print(box.height)
78
print('grow')
79
grow_rectangle(box, 50, 100)
80
print(box.width)
81
print(box.height)
82
83
84
if __name__ == '__main__':
85
main()
86
87
88