Reputation: 1014
I have been given instructions to "write a program that asks the user to enter values for mass and velocity, and then calls the kinetic_energy function to get the object's kinetic energy."
I have written code that is logically correct but I am wondering if I have the syntax backwards then what is described in the instructions. I believe my main function is calculating the result and simply passing it to the kinetic_energy function. I believe the instructions are asking for it to be done in the reverse order. If my assumption is correct how would I rewrite it to comply with the instructions?
#Gets the inputs from the user for mass and velocity
def main():
mass = int(input('Please enter the objects mass in kilograms: '))
velocity = int(input('Please enter the objects velocity in meters per second: '))
#Calculates the kinetic energy
kinetic_energy(ke = .5 * mass * velocity ** 2)
#Calculates the kinetic energy
def kinetic_energy(ke):
print ('The amount of kenetic energy is ',format(ke,',.2f'),sep='')
main()
Upvotes: 0
Views: 3563
Reputation: 3457
Typically you write functions that do "work".
So if you have a kinetic_energy
function, you wnat that function to do some more work than just printing.
So, it'd be more appropriate to rewrite your stuff as:
#Gets the inputs from the user for mass and velocity
def main():
mass = int(input('Please enter the objects mass in kilograms: '))
velocity = int(input('Please enter the objects velocity in meters per second: '))
#Calculates the kinetic energy
kinetic_energy(mass, velocity)
#Calculates the kinetic energy
def kinetic_energy(mass, velocity):
ke = .5 * mass * velocity ** 2
print ('The amount of kenetic energy is ',format(ke,',.2f'),sep='')
main()
Upvotes: 1
Reputation: 531235
You define kinetic_energy
as a function that takes two arguments, mass and velocity, then returns the computed value:
def kinetic_energy(m, v):
return .5 * m * v ** 2
Then you call the function from main
:
def main():
mass = int(input('Mass in kilograms: '))
velocity = int(input('Velocity in m/s: '))
ke = kinetic_energy(mass, velocity)
print('Kinetic energy is {.2f}'.format(ke))
main()
Upvotes: 2