Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NameError: global name 'reduce' is not defined

Tags:

python

reduce

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() 
like image 728
anhldbk Avatar asked Apr 19 '12 10:04

anhldbk


People also ask

How do you solve NameError name is not defined?

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.

How do you correct a NameError in Python?

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.

What is reduce in Python?

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.


1 Answers

I'm going to guess that:

  1. You are using Python 3, and
  2. You are following a tutorial designed for Python 2.

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)) 
like image 56
Greg Hewgill Avatar answered Oct 03 '22 02:10

Greg Hewgill