Home
 
 
Search:  
C C++ Perl PHP Python HTML ShellScripts
 
 
  Coding Books
  Tutorials
  Search Code
  Browse Code
  Link to Us
  Site News
  Contact Metalshell
 
 
 
  Submit Code   Statistics
 



Python 2.1 Bible    (ISBN: 0764548077)


 

 List Price: $39.99
 Our Price: $27.99
 Used Price: $21.00

 Release Date: June, 2001
 Manufacturer: John Wiley & Sons (Paperback)
 Sales Rank: 32,085

 Author: Dave Brueck, Stephen Tanner









More Info

 While Loop 2002-03-14 03:17:04
  python 
Category: source:python:general
Description: How to do while loops using python.
Platform: unix
Author: mind
Viewed: 16608
Rating: 3.8/5 (24 votes)
If you have any questions about this piece of code or still need help, try posting your question on the forum.

 

Printable Version
while.py
#!/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"
Rate this code:
(Not Helpful)  (Very Helpful) 

 
 
   Developer.*  
   Blue Parrots  
   Technipal  
   Defy Magazine  
   Code Project  
   Prog. Heaven  


Got Money?