Python 3 Count updating within function, but value doesn't update outside of it

python function not returning value
python for loop counter variable
count + 1 python
python returns none instead of value
python check if function returns true
counter variable python
python global variables
python for loop iteration count

I'm guessing that there is a scope issue here that I missed somewhere. This function squares all of the numbers and adds them together. It should stop if the number hits 1 or 89, otherwise keep going. Here's my code:

count = 0
def chain(x,count):
    x = str(x)
    temp = 0
    for let in range(0,len(x)):
        temp = temp + (int(x[let]) ** 2)
    x = temp
    print("\n")
    print(temp)
    if x == 89:
      count = count + 1
      print(count)
    elif x == 1:
      return False
    else:
        chain(x, count)

 chain(145, 0)

  print(count)

The problem is, when I print count when x == 89, I get 1. But when I print count at the end, it comes out as 0. I've looked over and I don't seem to be setting it to anything else, and I've also tried adding in return, return count, return True, and nothing seems to fix it. If someone could point out my error, I would greatly appreciate it!

Solution 1: make count a global variable

count = 0
def chain(x):
    global count
    x = str(x)
    temp = 0
    for let in range(0,len(x)):
        temp = temp + (int(x[let]) ** 2)
    x = temp
    print("\n")
    print(temp)
    if x == 89:
      count = count + 1
      print(count)
    elif x == 1:
      return False
    else:
        chain(x)

chain(145)

print(count)

Solution 2: return count and receive it when recursively called.

def chain(x,count):
    x = str(x)
    temp = 0
    for let in range(0,len(x)):
        temp = temp + (int(x[let]) ** 2)
    x = temp
    print("\n")
    print(temp)
    if x == 89:
      count = count + 1
      print(count)
    elif x == 1:
        pass  # you may want to use -1 or something as flag
    else:
      count = chain(x, count)
    return count


print(chain(145,0))

6. Iteration, Python 3 Count updating within function, but value doesn't update outside of it. python global variables python for loop count + 1 python python for loop counter​  Description. The count() method returns count of how many times obj occurs in list.. Syntax. Following is the syntax for count() method −. list.count(obj) Parameters. obj − This is the object to be counted in the list.

These are two different variables with the same name. the count outside the function will not change when the count inside the function will so printing at the end will give 0

Learning with Python 3, In Python, an assignment statement can make two variables equal, but they don't have If you try to update a variable that doesn't exist, you get an error, because Python For example, if the starting value (the argument passed to sequence) is 3, the The following function counts the number of decimal digits in a positive  Python Dictionary update() The update() method updates the dictionary with the elements from the another dictionary object or from an iterable of key/value pairs. The update() method adds element(s) to the dictionary if the key is not in the dictionary.

Well, the count is not exactly a reference since it's a primitive, so you don't get the same object every time (it is immutable).

Also, the count you are referencing outside of the function is not the same you pass initially (since your first call feeds it a 0, not the same variable).

  1. Make count a global variable by removing it from the function parameters and using the modifier global

Example

count = 0
def chain(x):
    global count
    ...
  1. Make the count a mutable type and pass it from the very beginning (e.g. a Class, a Dict, a list).

Example

line 01: count = {'total': 0}
line 20: chain(145, count)

Tutorial: Why Functions Modify Lists, Dictionaries in Python, But if the function should return a value, make sure all execution paths do We often want to know if some condition holds for any item in a list, e.g. “does the list The expression count > 0 evaluates to a Boolean value, either True or False. In addition, Python has built-in functions for finding the length of a sequence and for finding its largest and smallest elements. Python Lists The list is the most versatile datatype available in Python, which can be written as a list of comma-separated values (items) between square brackets.

Variables and scope, In this beginner Python tutorial, we'll take a look at mutable and immutable But what they do with our data can be a little confusing, and if we're not aware of to a variable like number_1 above inside a function doesn't affect its global value. and then iterate over each value in the dictionary, adding them to the count so  As we can see above, the function worked correctly, and the values of the global variables number_1 and number_2 did not change, even though we used them as arguments and parameter names in our function. This is because Python stores variables from a function in a different memory location from global variables. They are isolated.

Explorations in Computing: An Introduction to Computer Science and , To define a new variable in Python, we simply assign a value to a label. Define three variables at once: count, result, total = 0, 0, 0 # This is equivalent to: When we call the function, the print statement inside outputs 3 – but why does the If we ever need to update our code with a new value for the maximum mark, we​  1. Extending Python with C or C++¶. It is quite easy to add new built-in modules to Python, if you know how to program in C. Such extension modules can do two things that can’t be done directly in Python: they can implement new built-in object types, and they can call C library functions and system calls.

Iteration, First, the Histogram class does not allow us to arbitrarily set a value for one of PythonLabs canvas the drawing is automatically updated when we call count. Use the view_histogram function to display the histogram: >>> view_histogram(​hist) hist.count(3) Another technique for testing whether the sequence of values in a  Python 3.5 documentation 2. Built-in Functions lists them all. If you think there's a lot, think again! Python actually doesn't give you a large number of built-in functions. That's because many useful functions are packaged into their own modules.

Comments
  • Thank you, this works perfectly! Since I'm relatively a beginner, which of the two solutions do you recommend using in most situations/ which is better practice?
  • Generally global variables can make things a mess. Try to read this question for detailed discussion. And I also recommend you to read some stuff about name binding in Python to understand what is happening in solution 2.