功能菜单选择

2024-04-20 10:48:04 发布

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

我对编码是新手,我决定先学习python。到目前为止我很喜欢。但说到函数,我发现自己碰上了一堵墙。 我的目标是创建一个函数,这样我就不需要键入 [chapter = raw_input("Select a chapter]使用,[c_selection()] 但我好像没法让它工作。我以前也没有参加过任何形式的论坛。因此,如果有某些东西,我需要在我的岗位上,请让我知道。谢谢您!你知道吗

def C_selection():
    chapter = raw_input("Select a chapter: ")


def menu ():
    print "Chapter 1"
    print "Chapter 2"
    C_selection()


chapter = "home"
while  1 == 1:
    if chapter == "home":
        menu()
    if chapter == "1":
        print "Welcome to chapter 1"
        print " 'home' back"
        C_selection()

Tags: 函数目标编码homeinputrawifdef
2条回答

你应该改变你的C\选择函数来返回章节。你知道吗

def C_selection():
    return raw_input("Select a chapter: ")

菜单功能还应返回章节。然后你的while循环可以变成

chapter = "home"
while  True:
    if chapter == "home":
        chapter = menu()
    if chapter == "1":
        print "Welcome to chapter 1"
        print " 'home' back"
        chapter = C_selection()

这样可以避免使用globals。作为旁注,while True和while 1==1是完全相同的,但while True是更传统的书写方式。你知道吗

必须在访问全局变量的函数中使用全局关键字。你知道吗

否则,将创建另一个变量,该变量是C\u selection函数的本地变量,当该函数返回时,对其所做的任何更改都将丢失。你知道吗

例如

chapter = "home"

def C_selection():
    global chapter
    chapter = raw_input("Select a chapter: ")


def menu ():
    print "Chapter 1"
    print "Chapter 2"
    C_selection()



while  1 == 1:
    if chapter == "home":
        menu()
    if chapter == "1":
        print "Welcome to chapter 1"
        print " 'home' back"
        C_selection()

相关问题 更多 >