如何返回函数的开头

2024-06-02 06:17:36 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图使Settings()函数返回Menu()函数,但Settings()只是从调用它的地方继续。
我只需要它返回到Menu()函数的顶部

代码如下:

def Menu():
   Clear()
   print("Hello, world!")
   print("\n1. Settings")
   print("2. Exit")
   Choice = input("\n>")
   try:
       type(int(Choice))
   except Exception as e: 
       print("Oh no!\n I`ve encountered an error!" + e)
       Menu()
   if Choice == 1:
       Settings()
   if Choice == 2:
       exit(0)

def Settings():
   Menu()

谢谢你的帮助


Tags: 函数代码helloworldinputifsettingsdef
3条回答

Choice的类型为str,因此无法正确比较,并且比较总是失败, 用Choice = int(Choice)将值强制转换为int

def Menu():
   Clear()
   print("Hello, world!")
   print("\n1. Settings")
   print("2. Exit")
   Choice = input("\n>")
   try:
       Choice = (int(Choice))
   except Exception as e:
       print("Oh no!\n I`ve encountered an error!" + e)
       Menu()
   if Choice == 1:
       Settings()
   if Choice == 2:
       exit(0)

def Settings():
   Menu()

使用while循环,并使用string方法.isdigit()检查用户是否输入了数字。此外,还应检查该选项是否为有效的菜单选项

注意:不要忘记将选项强制转换为int,否则您的条件语句将不会执行

def Menu():
    while True:
        Clear()
        print('Hello, world!\n')
        print('1. Settings')
        print('2. Exit')
        
        choice = input('> ')
        if choice.isdigit() and int(choice) in {1, 2}:
            choice = int(choice)
            break
        else:
            print("Please enter 1 or 2")
            input('press enter to continue...')
    
    
    if choice == 1:
        Settings()
    if choice == 2:
        exit(0)

如果已检查用户输入是否有效,并已将其转换为int,则可以使用如下字典:

switch = {
    1: Settings
    2: exit
}

然后您可以替换菜单中的if语句,如下所示:

def Menu():
    while True:
        Clear()
        print('Hello, world!\n')
        print('1. Settings')
        print('2. Exit')
        
        choice = input('> ')
        if choice.isdigit() and int(choice) in {1, 2}:
            choice = int(choice)
            break
        else:
            print("Please enter 1 or 2")
            input('press enter to continue...')
    
    switch[choice]()

只需永远循环菜单():

def Menu():
   Clear()
   print("Hello, world!")
   print("\n1. Settings")
   print("2. Exit")
   Choice = input("\n>")
   try:
       type(int(Choice))
   except Exception as e: 
       print("Oh no!\n I`ve encountered an error!" + e)           
   if Choice == 1:
       Settings()
   if Choice == 2:
       exit(0)

def Settings():
   pass # do the settings stuff

while True:
    Menu()

相关问题 更多 >