0

In Python IDLE Shell it seems I cannot use a compound conditional expression and a while loop. I tried it within brackets too. Take these two examples:

k=0
m=0
while k<10 & m<10:
    print k
    k +=1
    m+=1

This doesn't evaluate the second condition. But if I write

 while k<10:
    print k
    k+=1

This does work. Is there a way I could achieve the first block of code with the "and" operator. I have done it in Java. Do I just need to put together "if" statements to achieve the same functionality in Python?

2
  • The answer to your question is given below by Deniz Dogan. But usually constructing while (or for) loops like this, i. e. by using a counter and incrementing it up to a certain value, is not Pythonic. You rather do a for x in range(10) or even better, for item in list_of_items, letting Python handle the iteration. Commented Jun 9, 2010 at 14:15
  • 1
    To add to Tim's comment, you can use for idx, elem in enumerate(my_list) to get both the 0-based "counter" in idx and the element at that index of the list in elem. Commented Jun 9, 2010 at 14:18

1 Answer 1

7

& should be and. & is the bitwise AND operator.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.