0

I want to make program which would begin with selecting mode. And then it should stay in that mode until i give to it command to go back to mode selection. Like that:

input=raw_input('Select mode, insert number of wanted mode: \n 1. first mode \n 2. second mode \n 3. Third mode\n')

if input=='1':
   while True:
      #code

if input=='2':
   while True:
      #code

if input=='3':
   while True:
      #code

Which is the best and shortest way to make it go back to mode selection with certain command?

Thanks

John Kugelman
  • 349,597
  • 67
  • 533
  • 578
user2904150
  • 149
  • 1
  • 1
  • 9
  • 3
    Tip: You should refrain from naming variables the same as one of the built-ins. Doing so overshadows them, thereby making them unusable in the current scope. –  Dec 13 '13 at 20:29

3 Answers3

3

Use break to go out of the (inner) while True loop:

while True:
    input=raw_input('Select mode, insert number of wanted mode: \n 1. first mode \n 2. second mode \n 3. Third mode\n')

    if input=='1'
       while True:
          #code
          if something_happens:
              break

    elif input=='2':
       while True:
           #code

    elif input=='3':
       while True:
           #code

For more information on break, see the official documentation here.

John1024
  • 109,961
  • 14
  • 137
  • 171
1

How about putting the mode select in its own function, then you can just call that function whenever you like?

def get_mode():
    input=raw_input('Select mode, insert number of wanted mode: \n 1. first mode \n 2. second mode \n 3. Third mode\n')
    return input
thumbtackthief
  • 6,093
  • 10
  • 41
  • 87
0

You should as mentioned in a comment avoid using built-in variable names like input.

A more right way to do this would be by a dictionary to select function, and an exception to handle unexpected input. All nested in a while loop in main.

I wrote up a short example, based pretty much on this: python - Simulating 'else' in dictionary switch statements

import sys

def mode1( arg = None ):
  return 'Mode1 completed'

def mode2( arg = None ):
  return 'Mode2 completed'

def mode3( arg = None ):
  return 'Mode3 completed'

def modeQuit ( arg = None ):
  sys.exit(0)

def main():
  menuText = "Select mode, insert number of wanted mode: \n 1. first mode \n 2. second mode \n 3. Third mode\n"

  # Function dictionary
  mode_function = {
      '1' : mode1,
      '2' : mode2,
      '3' : mode3,
      'q' : modeQuit
      }

  data=None

  print mode_function

  while True:
    mode_selection = raw_input(menuText).strip()
    try:
      print mode_function[mode_selection](data)
    except KeyError:
      print 'Not a valid mode'

  return 0

if __name__ == '__main__':
  main();
Community
  • 1
  • 1
Trygve
  • 493
  • 3
  • 15