python3 TypeError: 'function' object is not iterable

Question:

What change is required in the source code?

def Update():
    print("update called")

for i in Update:
    print(i)

Exception:

Traceback (most recent call last):
  File "example.py", line 4, in <module>
    for i in Update:        
TypeError: 'function' object is not iterable
Asked By: Droid

||

Answers:

What the traceback error is pointing out is the misuse of for statement:

for i in Updt():

for in python 3 is as follows: "Python’s for statement iterates over the items of any sequence (a list or a string), in the order that they appear in the sequence." (source: python 3.3 tutorial, section 4: More control structures Python 3

Since a function is neither a list nor a string, you can’t use the format:

for [variable] in [function]():

As far as what needs to be fixed, it depends on what those two functions are supposed to accomplish individually.

Answered By: user3460822

So let’s break down the error.

TypeError: ‘function’ object is not iterable

This error points to the line

for i in Update()

You always want the Object after in to be an iterable, meaning something that you can loop through. Because you don’t actually return anything in your Update() function. Python tries to loop through an object of type NoneType which is not allowed.

Answered By: Neel Sandell
import os

def Update():
    print('n')
    print("Update")
    cmd = os.system('xterm -e apt-get update')
    print("Finish update")


def AptUpdate():
    print('n')
    print("Update system? {Y/N}")
    print("Y or y")
    print("N or n")
    code = input("Command > ")
    if code == 'y' or code == 'Y':
        for i in Update():
            print(Update)
    elif code == 'n' or code == 'N':
        return
    else:
        print("Warning!")


AptUpdate()

Prints "Finish update" but you will get another error

Answered By: TwilightWolf