Search code examples
pythonfor-looptypeerror

Using the 'And' Operator in a For-Loop in Python


So I'm a bit curious about why this doesn't work.

How come code like:

for a in range(10) and b in range(10):
  print a + b

generates an error that says 'b is not defined'?

Also, code like:

for a,b in range(10):
  print a + b

generates an error: 'int objects are not iterable'.

Why? I haven't established their value beforehand, so how would Python know they are int objects? Also, I know you could use a while loop instead, but is there any way to carry out the sort of operation I'm doing using a for-loop alone?


Solution

  • for a,b in zip(range(10),range(10)):
        print a + b
    

    should work great... assuming I understood your question properly if not then

    for a in range(10):
        for b in range(10):
            print a+b
    

    or even [a+b for a in range(10) for b in range(10)]