Ryan Rampersad
Thoughts, opinions, ideas and now links
  • About
  • Podcast
  • Links

Do-While Loop in Python

April 15, 2012

There is honestly no do ... while loop in python. But you can simulate the behavior. The do-while loop is useful when the first iteration of a loop will usually suffice, the condition will be met, but not always. You can break out early.

while True:
  if 5 == input("enter a number, 1-10"):
    print "you got it"
    break
  else:
    print "keep trying"

It’s not a perfect do-while clone, but it works great.

Tagged: do, loops, python, while
<Previous Next>

© 2013 Ryan Rampersad.