Nil
Nil

Reputation: 39

Python functions and variables trouble

I have created this code so far...

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...]

Basically when I test it, I press option 2 first and it should give the output 'Please enter a sentence first!', which it does.

I then press option 1 in the menu and it should prompt me to input a sentence (I put 'my name is bob' as a test) and it does.

I then pressed option 2 after inputting the sentence and it should continue with my code - instead it gives the error message 'Please enter a sentence first!'

How can I fix this??

Upvotes: 0

Views: 80

Answers (2)

rainer
rainer

Reputation: 7099

You're setting a local variable sentence inside function option1. This variable is not visible in option2 since it lives inside option1 only and will be cleaned up once option1 is finished.

If you want to share the variable, you need to define it as global at least in option1:

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

Note, however, that using global variables is usually a sign of bad code quality. In your case, it would make more sense to have option1 return sentence to main, and pass it from main to option2.

Upvotes: 2

Will
Will

Reputation: 4469

Your issue is in assigning a value to sentence. Since you are assigning it in a function, when you leave that function's scope, you lose the value. Try using 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()

Or you could pass it back and forth with parameters.

Upvotes: 1

Related Questions