0

I'm having a little trouble translating C++ to python. The trouble I have is with the boolean statements in the for loop for (Nbound = 1; Nbound < (Nobs + 1) && B < Beta; Nbound++) and for (Ndm = 0;(Ndm < (i + 1) && P3 > (0)) || PP == 0; Ndm++). I'm unsure how this would work in python, I don't think python allows boolean statements in a for loop, so I think I would have to call it inside with an IF statement, but I'm not entirely sure. Thanks for your help!

also, I've noticed a lot of empty variables in this code for example, float PP is there a way of doing this in python or would I just assign it a value of 0 then change it later?

    float Pf = 0; //The complement of Beta
    float B = 0; //Beta
    float P3;
    float PP;
    float Nbound = 1;
    for (Nbound = 1; Nbound < (Nobs + 1) && B < Beta; Nbound++) {
        int Ndm = 0;
        int Nbgd = Nobs; //Setting Ndm=Nobs
        Pf = 0; //Zeroing the placeholder for the sum
        float exp; //A variable to store the exponential
        for (int i = 0; i < (Nobs + 1); i++) //Summing over Nbgd+Ndm<NObs
        {
            P3 = 1;
            PP = 0;
            if (P1[Nbgd] > 0) {

                for (Ndm = 0;(Ndm < (i + 1) && P3 > (0)) || PP == 0; Ndm++) {
                    //P3 = dist(Ndm, Nbound);
                    Pf = Pf + (P1[Nbgd] * P3); //Summing over the probability
                    PP = PP + P3;
                }

            }

        }
    }
}
3
  • 2
    python does have while loops and any for loop can be transformed to an equivalent while loop Commented Jun 14, 2021 at 14:55
  • you could use for Nbound in range(1, Nobs + 1): if B >= Beta: break Commented Jun 14, 2021 at 15:23
  • Aside: none of B, Beta, P3 nor PP influence the loop conditions here, so it can be for Nbound in range(1, Nobs + 1): for i in range(0, Nobs + 1): for Ndm in range(0, i + 1): Commented Jun 14, 2021 at 15:52

1 Answer 1

5

For loops in Python are meant for iteration over objects. If you want a loop with specific exit condition then you should use the while loop.

for loops in C can be described as :

for {initialization_statement; condition_expression; update_statement)
{
    body_statement_1;
    body_statement_2;
    ...
    body_statement_n;
}

The corresponding loop in Python is :

initialization_statement
while condition_expression:
   body_statement_1
   body_statement_2
   ...
   body_statement_n
   update_statement
Sign up to request clarification or add additional context in comments.

2 Comments

Aside: The C++ standard defines a for loop in terms of a while loop (with a slightly special handling of continue)
Thanks Caleth. Interesting point I did not know.

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.