Function recalling a variable

def length()
len(x)

def main():
x = str(input(“entrer a word:”))
length()

I get an error message when it runs the length() function saying x is not defined. How can i get a function to pull a user defined variable

If you bind (assign) to a name in a function, Python will assume that the name is local unless you declare that it’s global or nonlocal.

In your code, the best solution is to pass the variable into the function through the parameter list.

You should get SyntaxError not NameError - length function doesn’t have colon.

If you solve your current name problem then you will have next one: length() function is not that useful. It doesn’t have explicit return so it returns None. Calling this function accomplishes very little.

In the future, please format your code as code by putting it within
“code fences”, triple backticks on their own line:

```
code goes here
```

Triple tildes ~~~ will also work.

Also if you get an error message, please copy and paste the full error, starting with the line “Traceback”, into code fences too. Errors are not always so easy to guess as this one.

In your “main” function x is a local variable, so it only exists inside the main function.

One solution is to make it a global variable:

def main():
    global x
    # There is no need to call str(), as input() already returns a string.
    x = input("enter a word:")
    length()

A better solution is to pass x as an argument to your “length” function, which will need to be given a parameter to accept the argument:

def length(obj):  # Declare that the function needs an argument.
    len(obj)

def main():
    x = input("enter a word:")
    length(x)  # Pass x as argument.


main()  # Run the main function.

If you do that, your input will be called “x” inside the main function, but will have a different name, “obj”, inside the length function.

If you run that code, you will see that main asks you to enter a word, and then apparently nothing further happens. That’s because you calculate the length of the input and do nothing with it, so the interpreter just throws it away. Let’s fix that:

def length(obj):  # Declare that the function needs an argument.
    return len(obj)

def main():
    x = input("enter a word:")
    y = length(x)  # Pass x as argument, store the returned result as y.
    print("the length of", x, "is", y)


main()  # Run the main function.