Basic While Loop sequence of iteration? - python

For the code below, after the first instance where the IF statement is false (i.e. for i=9), I understand that we go to the print("something") step however, my question is why does it infinitely print "something" and "somethingelse" instead of printing these two just once each then just ending? I mean we have no step after the print of these two that tells it to go back to the if statement and test again with i = 9 (that would lead to an infinite loop)..
i=1
while True:
if i%9 != 0:
print ("inside if")
i +=1
continue
print("something")
print("somethingelse")

Your print statements are inside of a While True: loop with no exit criteria. That is precisely why.

while True:
Means that while I do not have a statement somewhere to stop or a break to stop the algorithm, it will keep entering in the while loop.
Therefore, what you made is an infinite loop and that's why it keeps printing the same stuff.
i=1
while True:
if i%9 != 0:
print ("inside if")
i +=1
break
print("something")
print("somethingelse")
#output
"inside if" -> breaks after `i=1` because `1%9=1`
"something"
"somethingelse"
i=1
kak = True
while kak:
if i%9 != 0:
print ("inside if")
i +=1
kak = False # --> something to tell the algorithm, hey! stop!
print("something")
print("somethingelse")

Related

Why does the while loop never stop looping?

Below is the snippet of my code. Let's assume that the output of play_again() inside the while loop returns False. Then, why does my while loop keep on looping? Is there is some concept I'm unaware of?
game_list = ['0','1','2']
while True:
position = myfunc()
replacement(game_list,position)
play_again()
print(game_list)
this is b/c the while True does not end unless you use the keyword break wich breaks outside the loop and continues the code.
the while True never ends
the while loop
while (condition):
#code
never ends until the condition is False, witch would never be true for the True condition.
do your code should be:
game_list = ['0','1','2']
while True:
position = myfunc()
replacement(game_list,position)
if not play_again():
break
print(game_list)
or you could do:
game_list = ['0','1','2']
while play_again():
position = myfunc()
replacement(game_list,position)
print(game_list)
This code should work:
while (play_again()):
position = myfunc()
replacement(game_list,position)
You should know that in Python a while loop (like in every other programming language) takes a single "argument", that is a condition of type bool:
while (i > 3): # i>3 is a boolean condition
...
In fact this is equivalent to
while (True): # the loop continues until condition is False, so in this case it will never stop
if (i > 3):
break
In Python break is a keyword that makes you exit the loop.
Then, as you probably understood, this code is equivalent to the first snippet in this answer:
while (True):
position = myfunc()
replacement(game_list,position)
if (not play_again()):
break
while True will run until you decide to break.
game_list = ['0','1','2']
while True:
position = myfunc()
replacement(game_list,position)
play_again = input("do you want to play again?")
if play_again == 'y':
play_again()
else:
break
print(game_list)

If statement returning False in While True loop (Python)

I expected that in this If statement, the variable 'i' would increment until it eventually equals 10, and subsequently 'if 10 < 10' would return False, breaking my while loop. But this code seems print until 10 and then get stuck in an infinite loop unless I add an else: break. Why?
i=0
while True:
if i < 10:
i = i + 1
print(i)
while X repeats when X equals to True so in while True it's always True. It only breaks with break statement.
In your code, you only check the value inside the while loop with if so neither you break the while loop nor you change True to False in while True.
If you want to use while:
i = 0
while i < 10:
i += 1
print(i)
Or
i = 0
while True:
if i < 10:
i += 1
print(i)
else:
break
Without while:
for i in range(10):
print(i)
while True
will make the loop run forever because "true" always evaluates to true. You can exit the loop with a break.
To achieve what you want to do, I would use
while i < 10:
print (i)
i++
That is because there isn't anything telling you to terminate the loop. So it will continue even after the if statement isn't satisfied.
This is why it is generally not a great practice to use while True
You can achieve the same thing with a for loop when the break condition is built into the loop:
for i in range(0, 10):
print(i)
If you want to use while True then you can go for:
i=0
while True:
i = i + 1
print(i)
if i == 10:
break
I think you need to understand a few things here, as you have set while True which means statement will never gets false so there is never end to while loop even if if condition gets fail. So the while loop will continue running till you interrupt.
The only way you can achieve this without break is like this, where you have a variable which will reset the condition of while loop to false when if loop fails
i=0
condition = True
while condition:
if i<10:
i=i+1
print(i)
else:
condition=False

Python break for loop

I am new to Python, but I think reserved words must have similar meaning in programming. However, I don't know why the break inside the 2nd if-condition breaks two for-loop.
I want to check if the list is empty or not, so I use a while-loop. It is supposed that if newList still has elements, it will stay in the loop2. However, after the break in con2, it goes directly to loop1 even newList still has element.
while list:
print ("loop1")
result = 'n'
for e in list:
print ("loop2")
result = 'n'
for h in longList:
print ("loop3")
for i in e.getList():
print ("loop4")
if (i == h.getId()):
print ("con1")
result = 'y'
break
if (result == 'y'):
print ("con2")
break
Your break statement is breaking from both loops because if you look just before you execute the first break statement, you assign the value y to the variable result. After you break from your first loop, the next line that gets tested is if (result == 'y'): and then you break again
while newList:
print ("loop1")
result = 'n'
for node in newList:
print ("loop2")
result = 'n'
for parent in parents:
print ("loop3")
for neighbourId in node.getNeighbours():
print ("loop4")
if (neighbourId == parent.getId()):
print ("con1")
result = 'y' # assignment
break # first break
if (result == 'y'): # occurs after the first break and will be true
print ("con2")
break # second break
else:
print('This loop was not terminated with a break statement')
else:
print('while loop ended')
Update:
In Python you can add an else clause to a loop and this else clause will only run if the loop has executed in full i.e never reached a break statement

Back in a code while loop

I have a problem in a simple code with while loop. My problem is explained in code comments.
CODE
exit = False
while not exit:
choice = input("Test ")
if choice== 1:
print "hello"
exit = False
else:
print "good morning"
#I want to return to the first while with the input Test but I pass to the second while
exit = False
exit1 = False
while not exit1:
choice = input("Test 1")
if choice== 1:
print "bye"
exit1 = False
else:
print "good evening"
#I want to return to the first while with the input Test but I return to the second while
exit = False
Thanks a lot.
I think what are you looking for are the continue and break statements.
The continue will interrupt the current iteration (and a new iteration is started, of course).
The break will interrupt the smallest enclosing loop.
Both statements work for for as well.
Take a look here for some reference.
outer = True
while outer:
do_something
if a:
continue # will get you back to do_something
if b:
break # will end the outer loop
If you set outer to False somewhere, it will end the while loop in the next iteration.

Does raw_input() stop an infinite while loop?

There is a small code below containing of while-loop.
question = raw_input("How are you? > ")
state = True
number = 0
print "Hello"
while True:
if question == "good":
print "Ok. Your mood is good."
state = False
question_2 = raw_input("How are you 2? > ")
elif question == "normal":
print "Ok. Your mood is normal."
elif question == "bad":
print "It's bad. Do an interesting activity, return and say again what your mood is."
else:
print "Nothing"
If I type in "normal", the program prints Ok. Your mood is normal. an infinite number of times.
But if I type in "good", the program prints Ok. Your mood is normal. and prints the contents of question_2.
Why is the question in question_2 = raw_input("How are you 2? > ") not repeated an infinite number of times?
Is it reasonable to conclude that raw_input() stops any infinite while loop?
No. It's not stopping the loop; it's actively blocking for input. Once input is received, it will not be blocked anymore (and this is why you get infinite text from other selections); there is no blocking I/O in those branches.
The reason you're not getting a lot of text output from option 1 is due to the way it's being evaluated. Inside of the loop, question never changes, so it's always going to evaluate to "good" and will continually ask you the second question1.
1: This is if it is indeed while True; if it's while state, it will stop iteration due to state being False on a subsequent run.
Once you've answered "good, the value returned by the second raw_input will be stored in variable question_2 rather than question. So variable question never changes again, but will remain "good". So you'll keep hitting the second raw_input, no matter what you answer to it. It doesn't stop your loop, but rather pauses it until you answer. And I think you should also take a good look at the comment of Alfasin...
You can stop an infinite loop by having an else or elif that uses a break for output. Hope that helps! :D
Example:
while True:
if things:
#stuff
elif other_things:
#other stuff
#maybe now you want to end the loop
else:
break
raw_input() does not break a loop. it just waits for input. and as your question is not overwritten by the second raw_input(), your if block will always end up in the good case.
a different approach:
answer = None
while answer != '':
answer = raw_input("How are you? (enter to quit)> ")
if answer == "good":
print( "Ok. Your mood is good.")
elif answer == "normal":
print( "Ok. Your mood is normal.")
# break ?
elif answer == "bad":
print( "It's bad. Do an interesting activity, return and say again what your mood is.")
# break ?
else:
print( "Nothing")
# break ?

Categories

Resources