I'm new to Python. Would you please tell me what's wrong with the following code? When I run it, I got an error message of "NameError: global name 'reduce' is not defined". I asked Goolge but it's useless. :(
def main(): def add(x,y): return x+y reduce(add, range(1, 11)) if __name__=='__main__': main()
The Python "NameError: name is not defined" occurs when we try to access a variable or function that is not defined or before it is defined. To solve the error, make sure you haven't misspelled the variable's name and access it after it has been declared.
You can fix this by doing global new at the start of the function in which you define it. This statement puts it in the global scope, meaning that it is defined at the module level. Therefore, you can access it anywhere in the program and you will not get that error.
Python's reduce() is a function that implements a mathematical technique called folding or reduction. reduce() is useful when you need to apply a function to an iterable and reduce it to a single cumulative value.
I'm going to guess that:
The reduce
function, since it is not commonly used, was removed from the built-in functions in Python 3. It is still available in the functools
module, so you can do:
import functools def main(): def add(x,y): return x+y functools.reduce(add, range(1, 11))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With