Writing Science Functions in Python

This is a practice checklist for writing functions in Python. We will use some common science equations as examples.

General rules for this assignment:

  • Every function must return a value. 
  • These functions should not print anything. Instead, they return values that can be printed in other parts of the program.
  • Each function must have parameters (input variables) defined in the function’s signature so that any input values can be used.
  • In a science class we would pay attention to the units of the variables (meters, kilograms, etc), but we will ignore the units to keep the programming simpler in this case.

1) Newton’s Second Law of Motion:

Create a function that can calculate the acceleration of an object given its mass and the net force on it.

a = \cfrac{F_{net}}{m}
Where:
a = acceleration of object
m = mass of object
F_net = net force on the object

Starter Code:

def a(f_net, m):
    #your code goes here

# If your code works properly, the following
# code will print the correct values
a1 = a(45.0, 3.0)
a2 = a(0.32, 0.16)
print(a1)    #15.0
print(a2)    #2.0

2) Gravitational Potential Energy

GPE = mgh
Where:
GPE = Gravitational Potential Energy
m = mass of the object
g = acceleration due to gravity = 9.8
h = height location of the object

In this case, one of the variables in the equation is known (g = 9.8), so you only need two parameters.

This time the method signature is not provided. If your code works, the test code below will work:

# Name your function to match the code below

mass1 = 28
height1 = 90
GPE1 = gpe(mass1, height1)
print(GPE1)

3) Kinetic Energy

KE = \cfrac{1}{2}mv^2
Where:
KE = kinetic energy
m = mass of object
v = velocity of object

Write the function and test it. You can use test code similar to what has been provided above.

4) Mechanical Energy

The mechanical energy of an object is the sum of its kinetic and potential energy. For this purpose, we will assume that it is the sum of GPE and KE, which are the previous two problems.

ME = KE + PE

You can call the previous two functions from inside your Mechanical Energy function.

5) Calling the kinetic energy function for every value in a list.

Use a loop to call your kinetic energy function on every value in the list given in the starter code below.
(The function call only needs to appear once in your code – don’t punish yourself by copying it over and over again…)

Starter Code:

# object's mass is given
mass = 3.25

# This list contains velocity data
vdata = [1, 1.5, 2.0, 2.5, 3.5, 3.7, 4.5, 5.9, 9.5, 11.0, 12.5, 13.2, 15.2, 20.1, 23.3, 25.8, 30.0]

# use a for loop to traverse the vdata list
# print the KE of the object for each velocity value

The output of your program should look something like this:

m = 3.25, v = 1.0, KE = 1.625
m = 3.25, v = 1.5, KE = 3.5625
m = 3.25, v = 2.0, KE = 6.5
...
...  # not all values shown
...
m = 3.25, v = 30.0, KE = 1462.5