Is the continue statement necessary in a while loop? - python

I'm confused about the use of the continue statement in a while loop.
In this highly upvoted answer, continue is used inside a while loop to indicate that the execution should continue (obviously). It's definition also mentions its use in a while loop:
continue may only occur syntactically nested in a for or while loop
But in this (also highly upvoted) question about the use of continue, all examples are given using a for loop.
It would also appear, given the tests I've run, that it is completely unnecessary. This code:
while True:
data = raw_input("Enter string in all caps: ")
if not data.isupper():
print("Try again.")
continue
else:
break
works just as good as this one:
while True:
data = raw_input("Enter string in all caps: ")
if not data.isupper():
print("Try again.")
else:
break
What am I missing?

Here's a really simple example where continue actually does something measureable:
animals = ['dog', 'cat', 'pig', 'horse', 'cow']
while animals:
a = animals.pop()
if a == 'dog':
continue
elif a == 'horse':
break
print(a)
You'll notice that if you run this, you won't see dog printed. That's because when python sees continue, it skips the rest of the while suite and starts over from the top.
You won't see 'horse' or 'cow' either because when 'horse' is seen, we encounter the break which exits the while suite entirely.
With all that said, I'll just say that over 90%1 of loops won't need a continue statement.
1This is complete guess, I don't have any real data to support this claim :)

continue just means skip to the next iteration of the loop. The behavior here is the same because nothing further happens after the continue statement anyways.
The docs you quoted are just saying that you can only use continue inside of a loop structure - outside, it's meaningless.

continue is only necessary if you want to jump to the next iteration of a loop without doing the rest of the loop. It has no effect if it's the last statement to be run.
break exits the loop altogether.
An example:
items = [1, 2, 3, 4, 5]
print('before loop')
for item in items:
if item == 5:
break
if item < 3:
continue
print(item)
print('after loop')
result:
before loop
3
4
after loop

Related

I can't reach a variable in a nested while loop

Here is the problem, it's just a simple program that rolls the dice, but when I write "no" in (want), the loop continues.
import random
play_continue = True
want = ""
want_play = False
while play_continue:
while not want_play:
try:
want = input("Do you want to play?: ")
except:
print("I don't understand what you said")
else:
if want == "no":
play_continue = False
elif want == "yes":
want_play = True
else:
print("I don't understand")
the reason is that you are still on the first step of the toplevel while loop, since the inner one is ongoing, even though you changed the value of play_continue the check never happens because the program never gets back around to it as the inner loop has yet to finish.
you can think of the whole inner loop as a single instruction such as
while play_continue:
do_stuff()
the play_continue condition is only checked once do_stuff() is completed, which in your case it is not

Using continue in while loop for python

My initial code...
name="LOVE"
i=0
while i < len(name):
i=i+1
if name[i] == "V":
print('Hi')
continue
print('Hello')#never printed
print(name[i])
print("The end")
The desired outcome is
L
O
Hi
E
The end
I have read other answers on this topic and I was either unable to understand or didn't find the answer I was looking for.
I know writing continue in while loop is bad practice, even so I wanted to know whether there was a way to use it without throwing an error(logical or IndexError) or going to an infinite loop.
'while'
as of my knowledge, doesn't have an option of
while(i++<len(name))
in python, so that didn't work.
Since the control is transferred to the beginning of the loop and test expression is not evaluated again,
I tried keeping the increment statement above the continue block and the print statement below to be logically consistent with the desired output.
First I lost 'L' in my output with 'IndexError' at 'if' statement and I was expecting the same error at print statement in the end. So I tried to improve by beginning index from -1 instead and catching my error.
name="LOVE"
i=-1
try:
while i < len(name):
i=i+1
if name[i] == "V":
print('Hi')
continue
print('Hello')#never printed
print(name[i])
except IndexError:
print()
print("The end")
In using for, the continue statement transfers control simply to next iteration in which by virtue of being the next iteration the counter(val) is already incremented so it works fluidly. Like below,
for val in "LOVE":
if val == "V":
print('Hi')
continue
print('Hello')#never printed
print(val)
print("The end")
Again I know of this but that is not what I am interested in...
In summary what I would like to know is if there is a more elegant way to do this without a try catch block, some other kind of implementation of continue in while to reach desired output in Python 3.x?
P.S:-this is my first question on this forum, so please go a bit easy on me.
You don't really need continue, just an else clause on your if statement. (Also, since i == 0 to start, you need to wait until you've used i as an index before incrementing it.)
name="LOVE"
i=0
while i < len(name):
if name[i] == "V":
print('Hi')
else:
print(name[i])
i=i+1
print("The end")
or
for c in name:
if c == "V":
print('Hi')
else:
print(c)
This really is a for job. You want an end to the looping, represented by both the except clause and the i < len(name) condition, and a loop increment, presented by the i=i+1 increment. Both of these tasks are typically performed by an iterator, and strings are iterable. It is possible to rewrite a for in while form, but it's not terribly meaningful:
i = iter(name)
while True:
try:
c = next(i)
except StopIteration:
break
print('Hi' if c == 'V' else c)
It's just much easier to write for c in name.
You could also use a finally, which should execute no matter how the try is left:
i = 0
while i < len(name):
try:
if ...:
continue
finally:
i += 1
The elegant (pythonic) way to solve this problem is to use for-loop, like others have suggested. However, if you insist on using while-loop with continue, you should try to tweak the condition of the while-loop. For example like this:
name="LOVE"
i=-1
while i < len(name)-1:
i=i+1
if name[i] == "V":
print('Hi')
continue
print('Hello')#never printed
print(name[i])
print("The end")
string="LOVE"
i=0
while i<len(string):
if string[i]=="V":
print("HI")
i+=1
continue
else:print(string[i])
i+=1
print("Thank You")

Python: How do I get my function to repeat until asked to cancel?

I just started learning Python. Basically I just want to repeat the loop once if answer is yes, or break out of the loop if answer is no. The return True/False doesn't go back to the while loop?
def userinfo():
while true:
first_name=input("Enter your name here:")
last_name=input("Enter your last name:")
phonenum=input("Enter your phone number here")
inputagain=rawinput("Wanna go again")
if inputagain == 'no':
return False
userinfo()
Instead of while true: use a variable instead.
Such as
while inputagain != 'no':
Instead of looping forever and terminating explicitly, you could have an actual condition in the loop. First assume that the user wants to go again by starting again as 'yes'
again = 'yes'
while again != 'no':
# ... request info ...
again = input("Wanna go again?: ")
though this while condition is a bit weak, if the user enters N, n, no or ever no with space around it, it will fail. Instead you could check if the first letter is an n after lowercasing the string
while not again.lower().startswith('n'):
You could stick to your original style and make sure the user always enters a yes-like or no-like answer with some extra logic at the end of your loop
while True:
# ... request info ...
while True:
again = input("Wanna go again?: ").lower()
if again.startswith('n'):
return # exit the whole function
elif again.startswith('y'):
break # exit just this inner loop

breaking out of the loop?

I'm having some trouble with breaking out of these loops:
done = False
while not done:
while True:
print("Hello driver. You are travelling at 100km/h. Please enter the current time:")
starttime = input("")
try:
stime = int(starttime)
break
except ValueError:
print("Please enter a number!")
x = len(starttime)
while True:
if x < 4:
print("Your input time is smaller than 4-digits. Please enter a proper time.")
break
if x > 4:
print("Your input time is greater than 4-digits. Please enter a proper time.")
break
else:
break
It recognizes whether the number is < 4 or > 4 but even when the number inputted is 4-digits long it returns to the start of the program rather than continues to the next segment of code, which isn't here.
You obviously want to use the variable done as a flag. So you have to set it just before your last break (when you are done).
...
else:
done = 1
break
The reason it "returns to the beginning of the program" is because you've nested while loops inside a while loop. The break statement is very simple: it ends the (for or while) loop the program is currently executing. This has no bearing on anything outside the scope of that specific loop. Calling break inside your nested loop will inevitably end up at the same point.
If what you want is to end all execution within any particular block of code, regardless of how deeply you're nested (and what you're encountering is a symptom of the issues with deeply-nested code), you should move that code into a separate function. At that point you can use return to end the entire method.
Here's an example:
def breakNestedWhile():
while (True):
while (True):
print("This only prints once.")
return
All of this is secondary to the fact that there's no real reason for you to be doing things the way you are above - it's almost never a good idea to nest while loops, you have two while loops with the same condition, which seems pointless, and you've got a boolean flag, done, which you never bother to use. If you'd actually set done to True in your nested whiles, the parent while loop won't execute after you break.
input() can take an optional prompt string. I've tried to clean up the flow a bit here, I hope it's helpful as a reference.
x = 0
print("Hello driver. You are travelling at 100km/h.")
while x != 4:
starttime = input("Please enter the current time: ")
try:
stime = int(starttime)
x = len(starttime)
if x != 4:
print("You input ({}) digits, 4-digits are required. Please enter a proper time.".format(x))
except ValueError:
print("Please enter a number!")

For Loop Not Breaking (Python)

I'm writing a simple For loop in Python. Is there a way to break the loop without using the 'break' command. I would think that by setting count = 10 that the exit condition would be met and the loop would stop. But that doesn't seem to be the case.
NOTE: Part of the challenge is to use the FOR loop, not the WHILE loop.
import random
guess_number = 0
count = 0
rand_number = 0
rand_number = random.randint(0, 10)
print("The guessed number is", rand_number)
for count in range(0, 5):
guess_number = int(input("Enter any number between 0 - 10: "))
if guess_number == rand_number:
print("You guessed it!")
count = 10
else:
print("Try again...")
count += 1
I'm new to programming, so I'm just getting my feet wet. I could use a 'break' but I'm trying figure out why the loop isn't ending when you enter the guessed number correctly.
The for loop that you have here is not quite the same as what you see in other programming languages such as Java and C. range(0,5) generates a list, and the for loop iterates through it. There is no condition being checked at each iteration of the loop. Thus, you can reassign the loop variable to your heart's desire, but at the next iteration it will simply be set to whatever value comes next in the list.
It really wouldn't make sense for this to work anyway, as you can iterate through an arbitrary list. What if your list was, instead of range(0,5), something like [1, 3, -77, 'Word', 12, 'Hello']? There would be no way to reassign the variable in a way that makes sense for breaking the loop.
I can think of three reasonable ways to break from the loop:
Use the break statement. This keeps your code clean and easy to understand
Surround the loop in a try-except block and raise an exception. This would not be appropriate for the example you've shown here, but it is a way that you can break out of one (or more!) for loops.
Put the code into a function and use a return statement to break out. This also allows you to break out of more than one for loop.
One additional way (at least in Python 2.7) that you can break from the loop is to use an existing list and then modify it during iteration. Note that this is a very bad way to it, but it works. I'm not sure that this will this example will work in Python 3.x, but it works in Python 2.7:
iterlist = [1,2,3,4]
for i in iterlist:
doSomething(i)
if i == 2:
iterlist[:] = []
If you have doSomething print out i, it will only print out 1 and 2, then exits the loop with no error. Again, this is a bad way to do it.
You can use while:
times = 5
guessed = False
while times and not guessed:
guess_number = int(input("Enter any number between 0 - 10: "))
if guess_number == rand_number:
print("You guessed it!")
guessed = True
else:
print("Try again...")
times -= 1
For loops in Python work like this.
You have an iterable object (such as a list or a tuple) and then you look at each element in the iterable, storing the current value in a specified variable
That is why
for i in [0, 1, 2, 3]:
print item
and
for j in range(4):
print alist[j]
work exactly the same. i and j are your storage variables while [0, 1, 2, 3] and range(4) are your respective iterables. range(4) returns the list [0, 1, 2, 3] making it identical to the first example.
In your example you try to assign your storage variable count to some new number (which would work in some languages). In python however count would just be reassigned to the next variable in the range and continue on. If you want to break out of a loop
Use break. This is the most pythonic way
Make a function and return a value in the middle (I'm not sure if this is what you'd want to do with your specific program)
Use a try/except block and raise an Exception although this would be inappropriate
As a side note, you may want to consider using xrange() if you'll always/often be breaking out of your list early.
The advantage of xrange() over range() is minimal ... except when ...
all of the range’s elements are never used (such as when the loop is
usually terminated with break)
As pointed out in the comments below, xrange only applies in python 2.x. In python 3 all ranges function like xrange
In Python the for loop means "for each item do this". To end this loop early you need to use break. while loops work against a predicate value. Use them when you want to do something until your test is false. For instance:
tries = 0
max_count = 5
guessed = False
while not guessed and tries < max_count:
guess_number = int(input("Enter any number between 0 - 10: "))
if guess_number == rand_number:
print("You guessed it!")
guessed = True
else:
print("Try again...")
tries += 1
What #Rob Watts said: Python for loops don't work like Java or C for loops. To be a little more explicit...
The C "equivalent" would be:
for (count=0; count<5; count++) {
/* do stuff */
if (want_to_exit)
count=10;
}
... and this would work because the value of count gets checked (count<5) before the start of every iteration of the loop.
In Python, range(5) creates a list [0, 1, 2, 3, 4] and then using for iterates over the elements of this list, copying them into the count variable one by one and handing them off to the loop body. The Python for loop doesn't "care" if you modify the loop variable in the body.
Python's for loop is actually a lot more flexible than the C for loop because of this.
What you probably want is to use break and to avoid assigning to the count variable.
See the following, I've edited it with some comments:
import random
guess_number = 0
count = 0
rand_number = 0
rand_number = random.randint(0, 10)
print("The guessed number is", rand_number)
# for count in range(0, 5): instead of count, use a throwaway name
for _ in range(0, 5): # in Python 2, xrange is the range style iterator
guess_number = int(input("Enter any number between 0 - 10: "))
if guess_number == rand_number:
print("You guessed it!")
# count = 10 # instead of this, you want to break
break
else:
print("Try again...")
# count += 1 also not needed
As others have stated the Python for loop is more like a a traditional foreach loop in the sense that it iterates over a collection of items, without checking a condition. As long as there is something in the collection Python will take them, and if you reassign the loop variable the loop won't know or care.
For what you are doing, consider using the for ... break ... else syntax as it is more "Pythonic":
for count in range(0, 5):
guess_number = int(input("Enter any number between 0 - 10: "))
if guess_number == rand_number:
print("You guessed it!")
break
else:
print("Try again...")
else:
print "You didn't get it."
As your question states NOTE: Part of the challenge is to use the FOR loop, not the WHILE loop and you don't want to use break, you can put it in a function and return when the correct number is guessed to break the loop.
import random
def main():
guess_number = 0
count = 0
rand_number = 0
rand_number = random.randint(0, 10)
print("The guessed number is", rand_number)
for count in range(0, 5):
guess_number = int(input("Enter any number between 0 - 10: "))
if guess_number == rand_number:
print ("You guessed it!")
return
else:
print("Try again...")

Categories