goto, cls, wait commands

Brian van den Broek bvande at po-box.mcgill.ca
Thu Feb 10 16:41:45 EST 2005


BOOGIEMAN said unto the world upon 2005-02-10 16:06:
> OK, thanks all
> Here's presentation of my advanced programming skills :)
> ----------------------------------------
> import os
> import time
> 
> os.system("cls")
> 
> number = 78
> guess = 0
> 
> while guess != number:
>     guess = input("Guess number: ")
>       
>     if guess > number:
>         print "Lower"
>         time.sleep(3)
>         os.system("cls")
> 
>     elif guess < number:  
>         print "Higher"
>         time.sleep(3)
>         os.system("cls")
> 
> print "That's the number !"
> ---------------------------------------
> BTW, I'm thinking to replace lines "time.sleep(3)"
> with something like "Press any key to guess again"
> How do I do that ?
> 
> Also I wanted to put at the end something like
> "Do you want to guess again ?" and then "GOTO" start
> of program, but since there is no such command in Python
> what are my possible solutions ?
> 

Hi,

I'm no expert and I owe much of whatever I know to the Python Tutor 
list. I'd suggest you check it out 
<http://mail.python.org/mailman/listinfo/tutor>.

As for your situation, I'd do something like this untested code:

guess = input("Guess number: ")
while guess != number:
     print `Nope.'
     guess = raw_input('Guess again? (Enter q for quit)')
     if guess.lower() == 'q':  # .lower() ensures 'Q' will match
         print `Quitter!'
         break
     if guess > number:
         # stuff here
     if guess < number:
         # different stuff here

raw_input is safer than input as it prevents malicious code from 
ruining your day.

A while loop is the usual way to repeat something until some condition 
is met. Here it repeats until guess == number. Another common idiom is

while True:
     # do some stuff
     if some_condition:  # some condition being True signals the
         break           # need to break out of the loop

I game to Python 10'ish years after I'd programmed some in BASIC and 
then not again. It took me a while to grok goto-less coding, too :-)

HTH,

Brian vdB




More information about the Python-list mailing list