Fatemeh
Fatemeh

Reputation: 63

How to stop the while loop?

Newbie in programming and need something like this but it doesn't stop the while condition even after entering a string starting with '0x', and it keeps calling the function.I tired putting 'break' instead of increasing i value, still didn't work. Any one knows why?

i = 1
while i < 2:
    call_fun1()
    if hx =='0x':
        i+=1

Upvotes: 1

Views: 160

Answers (2)

Sureshkumar Saroj
Sureshkumar Saroj

Reputation: 109

The above code will run into an infinite loop only when the while condition

while i < 2:

always turns out to be true. This will happen when the code section that is changing the value of i, i.e.

i+=1

is never executed. This will happen when the if condition

if hx =='0x':

always turns out to be false.

So check why

if hx =='0x':

is always evaluated to false. This should fix the problem.

Upvotes: 1

Alfie
Alfie

Reputation: 2350

With if hx =='0x', you are checking if hx equals "0x", not if it starts with it. You need to find a 'substring'. Check this question: Examples for string find in Python

Because of this, i is never incremented and therefore the loop will continue indefinitely.

Upvotes: 0

Related Questions