Help with name error: name "m" is not defined

Please help me with this error. Here is my code:

# function for calculating kinetic energy
def cal_kinetic_energy(m, v):
# kinetic energy formula
    return 0.5 * m * v**2

# main function
def main():
# input mass from user
    m = input("Please enter the mass (kg): ")
# input velocity from user
    v = input("Please enter the velocity (m/s): ")

# call kinetic energy method
**print( cal_kinetic_energy(m, v), "is the calculated kinetic energy")**

# call main
main()

I need help with line 14:: print( cal_kinetic_energy(m, v), “is the calculated kinetic energy”)

Here is what it says in the program:

Traceback (most recent call last):
File “C:\Users\user\PycharmProjects\pythonProject\add.py”, line 14, in
print( cal_kinetic_energy(m, v), “is the calculated kinetic energy”)
NameError: name ‘m’ is not defined

the m and v have a local scope, these variable only exists within the body of the function

why is the cal_kinetic_energy then outside/after the body of main function?

I think you’ve done c++/c before and you’re confusing it with python
You don’t need your def main() function!
The reason it says m and v are not defined, is that they only exist within your def main() and not outside of it.
if you do it like the following, you won’t get an error:

# function for calculating kinetic energy
def cal_kinetic_energy(m, v):
# kinetic energy formula
    return ((0.5 * m )* v**2)

# input mass from user
m = input("Please enter the mass (kg): ")
# input velocity from user
v = input("Please enter the velocity (m/s): ")

# call kinetic energy method
res = cal_kinetic_energy(m,v)
print( res + "is the calculated kinetic energy")

true, you don’t. But using a main function is still common practice, and I think its good practice, In fact, I would take it even a step further:

if __name__ == "__main__":
    main()

this ensures the main function only runs when the script/module is executed, but not when imported by another module/script

2 Likes