-2

Why the users input give me error under print ?

def num(n):
    sum = n * 5
    print("Amount of n is:", sum)
    user = float(input("Specify any number: "))

num(user)

NameError: name 'user' is not defined

but why it works under def?I would like to know the logic behind it?

def num(n):
    sum = n * 5
    print("Amount of n is:", sum)
user = float(input("Specify any number: "))

num(user)

The resut is:

Specify any number: 10
Amount of n is: 50.0
           
    
AMC
  • 2,642
  • 7
  • 13
  • 35
tony75
  • 5
  • 3
  • 1
    Because user variable was in-scope of the function in the latter case; – Aditya Jun 26 '20 at 19:12
  • Does this answer your question? [I'm getting an IndentationError. How do I fix it?](https://stackoverflow.com/questions/45621722/im-getting-an-indentationerror-how-do-i-fix-it) – Marsroverr Jun 26 '20 at 19:13
  • What do you understand from that error message? – AMC Jun 26 '20 at 21:02
  • Does this answer your question? [Python NameError: name is not defined](https://stackoverflow.com/questions/14804084/python-nameerror-name-is-not-defined) – AMC Jun 26 '20 at 21:03

3 Answers3

2

Indentation in Python matters, and affects how variables are scoped.

In the first example you posted, user is defined inside the scope of the num function (inside the indented block under the def), so it only exists inside that function. Furthermore, it doesn't exist until the function is called, so when you call num(user), you're trying to pass num a value that doesn't exist.

In the second example, you define user outside the function (at the module scope, with no indentation), so it's available to the subsequent line of code at the same scope.

Marsroverr
  • 556
  • 1
  • 6
  • 23
Samwise
  • 68,105
  • 3
  • 30
  • 44
1

The output shows an error beacuse you are trying to access a local variable "user" in a global scope whereas the local variable only works inside the function. When you declare a variable inside the function's body, we call it as a local variable.

fuat
  • 31
  • 1
-1

@Samwise answered your question in a clear way. But if you definetly wanted to take the input with in the function just do this

user = 1           # just for a variable need to pass into function
def num(n):
    global user
    n = float(input("Specify any number: "))
    sum = n * 5
    print("Amount of n is:", sum)
    

num(user)
Pavan kumar
  • 478
  • 3
  • 16