回到代码的开头

时间:2013-12-13 20:23:36

标签: python

我想制作以选择模式开始的程序。然后它应该保持在该模式,直到我给它命令返回到模式选择。像那样:

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

使用某个命令返回模式选择的最佳和最短方法是什么?

由于

3 个答案:

答案 0 :(得分:3)

使用break退出(内部)while True循环:

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

有关break的详细信息,请参阅官方文档here

答案 1 :(得分:1)

如何将模式选择放在自己的函数中,然后你可以随时调用该函数?

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

答案 2 :(得分:0)

您应该在评论中提到避免使用内置变量名称,例如input

更多正确的方法是通过字典来选择函数,以及处理意外输入的异常。全部嵌套在main中的while循环中。

我写了一个简短的例子,基于这个: 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();