简体   繁体   中英

Python - Function

I'm new to Python which I'm currently studying function. I'm coding mile to kilometer conversion with a constant ratio number and constant value for "mile" using the 'def_function' This is code.

mile=12

def distance_con(mile):
    km = 1.6 * mile
    print(km)
    return km

result=distance_con(mile)
print(result)

But i noticed that, if i delete 'return km' from the function and also result=distance_con(mile)

mile=12

def distance_con(mile):
    km = 1.6 * mile
    print(km)


print(km)

i get this errors "NameError: name 'km' is not defined "Assiging result of a function call, where the function has no return"

Kindly assist me to understand why the nameError, Because km is defined as 1.6*mile in the function and also assigning result of a function call error

I want to understand when and how to use the def_func and also any other materials to assist me understand python.

you got the error at print(km) km is define within the function scope so that you cannot access outside the function that you created.

In python there's a scope for a variable that we created see https://www.datacamp.com/tutorial/scope-of-variables-python for more info

You are trying to print something in the global namespace that is not defined in the global namespace.

The variable km only exists within the scope of the function. Your code doesn't reference the function, so it executes no differently than if the function wasn't there, like this:

mile = 12

print(km)

Since km was never defined outside the function it is an error.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM