2017-03-08 96 views
0

我到目前为止创建此代码...Python函数和变量麻烦

def print_slow(str): 
    for letter in str: 
     sys.stdout.write(letter) 
     sys.stdout.flush() 
     time.sleep(0.005) 

def menu(): 
    print_slow("-------------[MENU]-------------") 
    print(" ") 
    print_slow("1) Enter a sentence.") 
    print(" ") 
    print_slow("2) Find the position of a word.") 
    print(" ") 
    print_slow("--------------------------------") 
    print(" ") 

    print_slow(">>> ") 
    choice = str(input(" ")) 
    print(" ") 
    time.sleep(0.5) 

    if choice == "1": 
     option1() 
    if choice == "2": 
     option2() 

def option1(): 
    print_slow("Enter sentence") 
    sentence = str(input(": ")) 
    print(" ") 
    menu() 

def option2(): 
    if not sentence: 
     print_slow("Please enter a sentence first!") 
     time.sleep(0.5) 
     print(" ") 

    else: 
     sentenceUppercase = sentence.upper() 
     [code goes on...] 

基本上当我测试了一下,我按选项2第一,它应该给输出“请先输入句子! ,它这样做。

然后我按下菜单中的选项1,它应该提示我输入一个句子(我把'我的名字是bob'作为一个测试),它会。

然后我在输入句子后按下了选项2,它应该继续我的代码 - 而是给出错误消息'请先输入一个句子!

我该如何解决这个问题?

+0

为什么你需要time.sleeps? – nbro

+0

这是我的代码的一部分,但这并不真正相关@nbro – Nil

+0

您是否已将'sentence'定义为全局变量?因为你向我们展示的代码应该给出一个错误,因为在函数'option2'中你正在检查'sentence'是否为True(或False),但是从你的代码看,'sentence'似乎没有被定义任何地方。换句话说,'option1'下的'sentence'是一个局部变量,而不是'option2'中的变量。 – nbro

回答

1

你的问题是在给sentence赋值。既然你在函数中分配它,当你离开函数的作用域时,你就失去了这个值。尝试使用global

sentence = '' 

def option1(): 
    global sentence    # <-- this maintains its value in global scope 
    print_slow("Enter sentence") 
    sentence = str(input(": ")) 
    print(" ") 
    menu() 

def option2(): 
    global sentence    # <-- and here 
    if not sentence: 
     print_slow("Please enter a sentence first!") 
     time.sleep(0.5) 
     print(" ") 
    else: 
     sentenceUppercase = sentence.upper() 

或者你可以传递参数来回传递它。

2

您正在设置本地变量sentence内部函数option1。该变量在option2中不可见,因为它只能在option1之内,并且在option1完成后将被清除。

如果你要共享的变量,你至少需要在option1将其定义为global

def option1(): 
    print_slow("Enter sentence") 
    global sentence 
    sentence = str(input(": ")) 
    print(" ") 
    menu() 

注意,但是,使用全局变量通常是不好的代码质量的标志。在你的情况下,option1返回sentencemain并将其从main传递到option2会更有意义。

+0

这很好,谢谢! @rainer – Nil