Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 351
Akshat Mahajan Avatar asked Sep 20 '25 11:09

Akshat Mahajan


1 Answers

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)]

like image 169
Joran Beasley Avatar answered Sep 23 '25 00:09

Joran Beasley