While Loop
2002-03-14 03:17:04
Category: python:general
Description: How to do while loops using python.
Author: mind
Viewed: 18466
Rating: (25 votes)


#!/usr/local/bin/python
#
# while example by mind@metalshell.com
#
# an example on while loops
#
# 03/12/2002
#
# http://www.metalshell.com
#
 
# import the sys module, so we can use system commands such as exit.
import sys
 
line = 0
max_lines = 10
 
# while line is under or not equal to max_lines, loop the bottom segment
while line < max_lines :
  # increase line by one
  line = line + 1
 
  print "Line",
  print line
 
# example on a while loop, this example will loop until the statement
# is true or the statement is stopped using 'break' or sys.exit()
 
secret_answer = "s3cr3t"
secret_question = raw_input("Enter secret answer: ")
 
if secret_answer != secret_question:
  while secret_answer != secret_question:
    secret_question = raw_input("Enter secret answer: ")
 
print "secret answer accepted"
 
# here is another example based on the above example, a tad bit more advanced.
 
secret_times = 0
secret_restrict = 3
secret_answer = "s3cr3t"
secret_question = raw_input("Enter secret answer: ")
 
if secret_question != secret_answer:
  secret_times = secret_times + 1
  while secret_question != secret_answer:
    if secret_times == secret_restrict:
      print "Sorry but you have failed to answer", secret_times,
      print "times"
      sys.exit()
 
    secret_question = raw_input("Enter secret answer: ")
    secret_times = secret_times + 1
 
if secret_times == 0:
  print "secret answer accepted on the first try"
else:
  print "secret answer accpeted after", secret_times,
  print "times"
 
# Here is an example on a never ending while loop, note: this will go
# on 'forever' hold ctrl and press c to stop it, otherwise it will
# more than likely run up your cpu and suck up all your memory.
 
line = 0
while 1 == 1:
  line = line + 1
  print "Looped: ",line,
  print "times"