Python Activity

In the recent python activity held in TP, I got 2 tasks. The first one is to calculate volumes of different shapes according to people’s choice.

After one hour of struggling, I finally figured it out with the help of teacher.(I’m still a beginner (: ) And the program looks like this:

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
import math

list_cube = []
list_pyramid = []
list_ellipsoid = []


while True:
command = input('you may choose from “cube” or “c”, “pyramid” or “p”, “ellipsoid” or “e”, “quit” or “q’; to calculate the volumes of the shapes:')
if command == 'cube' or command == 'c':
a = int(input('please input a positive number:'))
volume_cube = a**3
list_cube.append(volume_cube)
print(volume_cube)

elif command == 'pyramid' or command == 'p':
b,h = input('please input its base b and height h:').split(',')
volume_pyramid = (1/3) * (int(b)**2 * int(h))
list_pyramid.append(volume_pyramid)
print(volume_pyramid)

elif command == 'ellipsoid' or command == 'e':
r1,r2,r3 = input('please input three radii for the ellipsoid:').split(',')
volume_ellipsoid = (4/3) * math.pi *int(r1) *int(r2) *int(r3)
list_ellipsoid.append(volume_ellipsoid)
print(volume_ellipsoid)

else:
print('byebye')
break


list_cube.sort()
list_pyramid.sort()
list_ellipsoid.sort()
print ('you have reached the end of your session.')
print ('the volumes calculated for each shapes are:')
print ('cube:',list_cube )
print('pyramid:',list_pyramid)
print('ellipsoid:',list_ellipsoid)

As for the second task, I was asked to write a program to use the Monte Carlo method to calculate the area of any irregular shape. However, because I was still a rookie, my teacher eased the task and I only had to calculate pi using this method.

The final result looks pretty simple, but took me a while to figure out):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
import random
import math
import tqdm

count = 0
n = 1000000

for i in tqdm.trange(0,n):
x = random.uniform(-0.5,0.5)
y = random.uniform(-0.5,0.5)
if math.sqrt(x**2 + y**2) <= 0.5:
count += 1

a = (count / n) *4
print (a)

It turns out that the atmosphere does helps with your study!