简体   繁体   English

回到代码开头

[英]Going back to beginning of the code

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 谢谢

Use break to go out of the (inner) while True loop: while True循环中使用break退出(内部):

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 . 有关break更多信息,请参见此处的官方文档。

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

You should as mentioned in a comment avoid using built-in variable names like input . 如注释中所述,您应该避免使用内置变量名(如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. 全部嵌套在main中的while循环中。

I wrote up a short example, based pretty much on this: python - Simulating 'else' in dictionary switch statements 我写了一个简短的示例,基于此: python-在字典切换语句中模拟“ else”

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();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM