Videos
What is a while loop in Python?
When should I use a while loop instead of a for loop?
How can I avoid infinite loops when using while loops?
I am not sure what you are trying to do. You can implement a do-while loop like this:
while True:
stuff()
if fail_condition:
break
Or:
stuff()
while not fail_condition:
stuff()
What are you doing trying to use a do while loop to print the stuff in the list? Why not just use:
for i in l:
print i
print "done"
Update:
So do you have a list of lines? And you want to keep iterating through it? How about:
for s in l:
while True:
stuff()
# use a "break" instead of s = i.next()
Does that seem like something close to what you would want? With your code example, it would be:
for s in some_list:
while True:
if state is STATE_CODE:
if "//" in s:
tokens.add( TOKEN_COMMENT, s.split( "//" )[1] )
state = STATE_COMMENT
else :
tokens.add( TOKEN_CODE, s )
if state is STATE_COMMENT:
if "//" in s:
tokens.append( TOKEN_COMMENT, s.split( "//" )[1] )
break # get next s
else:
state = STATE_CODE
# re-evaluate same line
# continues automatically
Here's a very simple way to emulate a do-while loop:
condition = True
while condition:
# loop body here
condition = test_loop_condition()
# end of loop
The key features of a do-while loop are that the loop body always executes at least once, and that the condition is evaluated at the bottom of the loop body. The control structure show here accomplishes both of these with no need for exceptions or break statements. It does introduce one extra Boolean variable.
I'm working on a pseudocode/flowchart for printing an enumerated shopping list and I'm having trouble figuring out how to show it in the flowchart. I have the code already made and it works, but I can't figure out the dang flowchart! If someone could help me out, I would appreciate it.
Here's an example of what I have in my code:
shopping_list = ["apples", "bananas", "pears"]
for count, value in enumerate(shopping_list, 1):
print("Item", count, "is", value)
And my result prints like:
Item 1 is apples
Item 2 is bananas
Item 3 is pears
The actual coding makes sense, but representing that sequence in a flowchart is confusing me because I don't know how to show the loop.