There is no do-while loop in Python.
This is a similar construct, taken from the link above.
while True:
do_something()
if condition():
break
Answer from theycallmemorty on Stack OverflowThere is no do-while loop in Python.
This is a similar construct, taken from the link above.
while True:
do_something()
if condition():
break
I prefer to use a looping variable, as it tends to read a bit nicer than just "while 1:", and no ugly-looking break statement:
finished = False
while not finished:
... do something...
finished = evaluate_end_condition()
Until statement/loop python? - Stack Overflow
Why there is no do while loop in python - Stack Overflow
python - How to emulate a do-while loop? - Stack Overflow
Python: Most efficient loop until condition - Stack Overflow
Videos
continue is a keyword that requires no arguments. It simply tells the current loop to continue immediately to the next iteration. It can be used inside of while and for loops.
Your code should then be placed within the while loop, which will keep going until the condition is met. Your condition syntax is not correct. It should read while response != 'exit':. Because you are using a condition, the continue statement is not needed. It will by design continue as long as the value is not "exit".
Your structure would then look like this:
response = ''
# this will loop until response is not "exit"
while response != 'exit':
response = raw_input("foo")
If you wanted to make use of continue, it might be used if you were going to do other various operations on the response, and might need to stop early and try again. The break keyword is a similar way to act on the loop, but it instead says we should immediately end the loop completely. You might have some other condition that is a deal breaker:
while response != 'exit':
response = raw_input("foo")
# make various checks on the response value
# obviously "exit" is less than 10 chars, but these
# are just arbitrary examples
if len(response) < 10:
print "Must be greater than 10 characters!"
continue # this will try again
# otherwise
# do more stuff here
if response.isdigit():
print "I hate numbers! Unacceptable! You are done."
break
Your while loop will continue until the condition you've set is false. So you want your code to mostly be inside this loop. Once it's finished, you know the user entered 'exit' so you can print the error message.
#!/usr/bin/python
friends = {'John' : {'phone' : '0401',
'birthday' : '31 July',
'address' : 'UK',
'interests' : ['a', 'b', 'c']},
'Harry' : {'phone' : '0402',
'birthday' : '2 August',
'address' : 'Hungary',
'interests' : ['d', 'e', 'f']}}
response = ['']
error_message = "Sorry, I don't know about that. Please try again, or type 'exit' to leave the program: "
while response[0] != 'exit':
response = raw_input("Please enter search criteria, or type 'exit' to exit the program: ").split()
try:
print "%s's %s is %s" % (response[0], response[1], friends[response[0]][response[1]])
except KeyError:
print error_message
except IndexError:
print error_message
print ('Thank you, good bye!')
This code is a start to what you want, but it still has some bugs. See if you can restructure it so the error message isn't printed when the user enters 'exit'.
There is no do...while loop because there is no nice way to define one that fits in the statement: indented block pattern used by every other Python compound statement. As such proposals to add such syntax have never reached agreement.
Nor is there really any need to have such a construct, not when you can just do:
while True:
# statement(s)
if not condition:
break
and have the exact same effect as a C do { .. } while condition loop.
See PEP 315 -- Enhanced While Loop:
Rejected [...] because no syntax emerged that could compete with the following form:
while True: <setup code> if not <condition>: break <loop body>A syntax alternative to the one proposed in the PEP was found for a basic do-while loop but it gained little support because the condition was at the top:
do ... while <cond>: <loop body>
or, as Guido van Rossum put it:
Please reject the PEP. More variations along these lines won't make the language more elegant or easier to learn. They'd just save a few hasty folks some typing while making others who have to read/maintain their code wonder what it means.
Because everyone is looking at it wrong. You don't want DO ... WHILE you want DO ... UNTIL.
If the intitial condition is true, a WHILE loop is probably what you want. The alternative is not a REPEAT ... WHILE loop, it's a REPEAT ... UNTIL loop. The initial condition starts out false, and then the loop repeats until it's true.
The obvious syntax would be
repeat until (false condition):
code
code
But for some reason this flies over everyone's heads.
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.
What you are doing is called "busy waiting". In order to do this without eating up CPU time, you should sleep for a short interval in each iteration of the loop:
while True:
if first_number == second_number:
do_something()
break
time.sleep(0.1)
Adjust the sleep interval as appropriate.
But there's likely a better way to accomplish what you want. How is first_number changing value if it's "out of your control"? Is your program receiving input? Reading from a socket? Are you sending a network request for data? Is this data shared among processes using multiprocessing's facilities?
Simply check if first number is not equal to the second number, in the while loop's condition itself.
while first_number != second_number:
print("You're in the lost forest\n" + "*" 25) print("" 25) print(" :-( ") print("" 25) print("" *25) print("Right or Left")
which_way = (str.capitalize(input ())) while which_way == "Right": print("HaHaHa!!! You are still in the forest!!!") break
Wouldn't a better way be to just use modulus.
>>> x = 2885
>>> y = 1440
>>> x%y
5
>>>
Or still using loops
>>> x = 2885
>>> y = 1440
>>> while x >= y :
... x = x - y
...
>>> x
5
>>>
Instead of True as the condition for execution, just put x > y:
x = 2885
y = 1440
while x >= y:
x -= y
>>x
Output:
5
Instead, you can use a while loop. What I mean here is you can simply:
principal = float(input("How much money to start? :"))
apr = float(input("What is the apr? :"))
amount = float(input("What is the amount you want to get to? :"))
def interestCalculator():
global principal
i = 1
if principal > amount:
print("Can't calculate interest. Error: Amount is less than principal")
while principal < amount:
principal = principal + principal*apr
print("After year " + str (i)+" the account is at " + str(principal))
if principal > amount:
print("It would take" + str(year) + " years to reach your goal!")
i += 1
interestCalculator()
A suggestion for a more pythonic solution
PRINCIPAL = float(input("How much money to start? :"))
APR = float(input("What is the apr? :"))
AMOUNT = float(input("What is the amount you want to get to? :"))
def interestCalculator(principal, apr, amount):
year = 0
yield year, principal
while principal < amount:
year += 1
principal += principal*apr
yield year, principal
for year, amount in interestCalculator(PRINCIPAL, APR, AMOUNT):
print(f"After year {year} the account is at {amount:.2f}")
if year == 0:
print("Can't calculate interest. Error: Amount is less than principal")
print(f"It would take {year} years to reach your goal!")