Replace for Goto
Gerhard Häring
gh at ghaering.de
Wed May 28 21:02:37 EDT 2003
Dvm5 wrote:
> I'm used to Basic. There is a Goto/Label command, you put goto where
> you want it to come from and label where you want it to go. Simple.
> How can I do this in Python?
You can't. This is a feature, not a bug ;-) With the control structures
Python offers (for loops, while loops, functions, exceptions), GOTO is
not necessary.
Where you'd have used goto in BASIC, you can most of the time find a
clearer form and use "break" and "continue" statements. For the few
cases where this is not possible and you don't want to introduce a
temporary boolean variable, you can use exceptions to break out of
nested loops, for example.
> What I'm trying to do is create a "play again" type user interface.
> Thus, I can't alter the program to use an If command; the option has
> to be at the end, and the effect has to be at the begining! How do I
> accomplish this?
Use a never-ending while loop, then use an "if" and a "break". Like this:
while 1:
# do stuff
answer = raw_input("Want to play again? (y/n)").upper()
if answer == 'N':
break
> If there is another way, other than a similar thing to Goto, tell me
> that, as well as a similar thing for goto. It would probably be useful
> later on...
See above. I'd suggest that you learn Python by following one of
tutorials at http://www.python.org/doc/Newbies.html
These will teach you the Pyhton way of doing things, which is better
than finding equivalents for what you did in BASIC.
-- Gerhard
More information about the Python-list
mailing list