[Tutor] Menu not working properly

Evert Rol evert.rol at gmail.com
Mon Aug 2 12:35:17 CEST 2010


> My problem is choice 3. Exit, if you select no or put an invalid answer... It will run menu1... but then it runs
>     name = raw_input ("Enter your character name. ")
>     print "Your character name is:", name
> 
> How can i make it so it prints menu1 like normal... then asks you to enter your selection again?
> instead of running the above code.

Put it in a loop with the necessary break statements. Something like:

while True:
  print menu1
  answer = raw_input()
  if ...:
    ...
    break
  elif ...: 
    ...
  elif ...:
   answer = raw_input()
   if ...:
     sys.exit()
raw_input('character name')

Only the first option will break out of the loop to the 'character name' question; the other two options will continue to loop, apart from the point where you exit() the whole program.
If you need user input until the correct input has been given, that means you'll have to wrap things in a loop (generally a while loop that you break out of when you received correct input). 
You could factor out the actual code inside the while loop into a function, which can make the structure clearer.


Btw, 

<snip />

>     characterChoice = input ("Enter your choice. ")

You have input() here, while further down raw_input(). The latter is preferred in Python 2.x. I assume this is just a minor mistake.


  Evert


>     print
> 
>     if characterChoice == 1:
>         print """
> 
> *Place Holder*                        
>                           
>         """
> 
>     elif characterChoice == 2:
>         print "Currently under construction.\nPlease choose again."
>         print menu1
>     elif characterChoice == 3:
>         endProgram = raw_input ("Do you want to end program? yes or no ")
>         if endProgram == "yes":
>             sys.exit(0)
>         elif endProgram == "no":
>             print menu1
>         else:
>             print "\nInvalid Command:\nSelect from the menu again.\n"
>             print menu1
>         
>     print    
>     name = raw_input ("Enter your character name. ")
>     print "Your character name is:", name
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor



More information about the Tutor mailing list