-1
while (/*condition include a*/):
    //for some reason has to create a in the process.

Recently I encountered a python program which has to be built that way. Finally I switched the method and avoid the problem. But it got me thinking what if we need a while statement but the condition of that statement is in the excution process of the statement. And it will give an error when we run it like a is not defined. So what can we do to make that work. I know it's a easy problem, I am a beginner so please help me if you want to, thank you!

chenxinru
  • 3
  • 1
  • 3

3 Answers3

3

I don't know exactly how was your problem but I think could do this

a = True
while a and other_conditions:
    a = get_a_value()
    # rest of the code

In this case I used boolean values, but a could take any value that doesn't affect the general condition (Like 1 in multiplication, or 0 for sums)

Mr. E
  • 2,070
  • 11
  • 23
1

I think you are talking about do-while loop when the first iteration should be executed anyway and then should be checked. If I am correct there is a good answer on this topic on SO already.

Community
  • 1
  • 1
max
  • 2,757
  • 22
  • 19
0

If I understand what you are asking, you simply need to initialize a to a value which will force the while loop to make at least one iteration. A very simple example:

a = 0
while a < 5:
    a += 1
chepner
  • 497,756
  • 71
  • 530
  • 681
  • Yes perhaps I simplified the situation too much. – chenxinru Jan 29 '16 at 07:23
  • The real situation is I have to initiate a list then append element to it.and then I tried to initiate a=[], but the condition check is need to check all the a[1],a[2],a[3], but if I only initiate an empty list it will still give me an error. And I if I initiate a = [ , , , ] with 4 empty elements, then after I append , I will have 8 element and it's not good. Finally I give up appending and just change the value of empty elements. But is there an easy way to use "do-while loop when the first iteration should be executed anyway and then should be checked"? – chenxinru Jan 29 '16 at 07:23
  • What *exactly* do you have to check? Something like `while any(predicate, a):` or `while all(predicate, a):` (where `predicate` is some Boolean function you can apply to each element of the list) may be what you want. – chepner Jan 29 '16 at 13:12
  • In general, you need to do two (related) things: initialize `a` to *some* list that can be checked, and generalized your check to handle a list whose size you don't know in advance. – chepner Jan 29 '16 at 13:16