Python 如何使用打印语句创建菜单?我希望能够选择一个数字,并根据我选择的数字运行该函数

Python 如何使用打印语句创建菜单?我希望能够选择一个数字,并根据我选择的数字运行该函数,python,function,menu,Python,Function,Menu,我希望这是一个输入语句,当我输入1时,它会像我在主程序中编码一样打印1234。。。帮助为什么当我输入1、2或3时,它除了打印结束外什么也不做。。?帮助 main您的line option=displaymenu将选项设置为None,因为您的函数末尾没有返回语句。 将以下行添加到函数中,它应该可以工作: def main(): option=displaymenu() print(option) while option1 != 4: if option1

我希望这是一个输入语句,当我输入1时,它会像我在主程序中编码一样打印1234。。。帮助为什么当我输入1、2或3时,它除了打印结束外什么也不做。。?帮助 main

您的line option=displaymenu将选项设置为None,因为您的函数末尾没有返回语句。 将以下行添加到函数中,它应该可以工作:

def main():

    option=displaymenu()
    print(option)
    while option1 != 4:
        if option1 ==1:
            print("1234")
        elif option1==2:
            print("1")
        elif option1==3:
            print("joe")
        else:
            print("end")



def displaymenu():
    print("choose one of the following options")
    print("1.Calculate x to the power of N")  << this is supposed to be 
    print("2.Calculate factorial of N")
    print("3.Calculate EXP")
    print("4.Exit")
    option1=input("Please enter your choice here:")<<<  i want these print statements to act as a menu? how do I make it so when I input a number 1-4 It does this operation I input ?

您没有从displaymeny返回选项1。而是尝试在主功能中访问它:

return int(option1)
这也意味着主功能中的选项没有任何值

将您的程序更改为:

 while option1 != 4:

还请注意,我在while循环中移动了对displaymeny的调用。如果您将其置于外部,则只能获得一次菜单。

是的,正如@Energya所提到的,您应该将输入转换为int。您能简单说明一下选项=-1的作用吗?谢谢@joekimoly只预设了值。您可以将其设置为除4之外的任何值。正如@abccd所说,这是一个起始值或预设值。当我们想要比较while循环中的选项时,变量必须存在,我们需要给它任何不是4的值,因为这将使程序永远不会进入循环。我使用-1表示这不是循环中使用的任何特定值。return int选项1只是返回输入正确的值@Energya@TeanteMclin是的,通过将return x放在某个函数foo的末尾,您可以使用return\u value=foo获得该值。int函数用于将您输入的字符串类型转换为int数,以确保菜单中的比较有效。如果答案回答了您的问题并且有用,请不要忘记将其标记为已接受!
def main():
option = -1 # Value to get the while loop started
while option != 4:
    option=displaymenu()
    if option ==1:
        print("1234")
    elif option==2:
        print("1")
    elif option==3:
        print("joe")
    else:
        print("end")



def displaymenu():
    print("choose one of the following options")
    print("1.Calculate x to the power of N")  << this is supposed to be 
    print("2.Calculate factorial of N")
    print("3.Calculate EXP")
    print("4.Exit")
    return input("Please enter your choice here:")<<<  i want these print statements to act as a menu? how do I make it so when I input a number 1-4 It does this operation I input ?