0

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.

Chris
38.3k6 gold badges33 silver badges59 bronze badges
asked Nov 22, 2022 at 1:54
7
  • Be reminded - function needs to be called, and in 2nd case, you did not call it. So km is unknown. (it's not related with missing return statement) Commented Nov 22, 2022 at 1:58
  • Variables only exist in the scope in which they're defined. Otherwise every variable named "x" or "I" in a million line program would be getting confused with one another. Commented Nov 22, 2022 at 1:59
  • 1
    Python Scopes and Namespaces Commented Nov 22, 2022 at 2:00
  • function defines its own scope for variables. km exists inside your distance_con function only. Commented Nov 22, 2022 at 2:00
  • Maybe read this article - realpython.com/python-scope-legb-rule Commented Nov 22, 2022 at 2:01

2 Answers 2

1

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

answered Nov 22, 2022 at 1:58
Sign up to request clarification or add additional context in comments.

Comments

1

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.

answered Nov 22, 2022 at 2:03

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.