2

So, I have this stuff below

def userinput():
    adjective1 = input("Adjective: ")
    noun1 = input("Noun: ")
    noun2 = input("Noun: ")

def story():
    print("A vacation is when you take a trip to some " + adjective1 + " place.")
    print("Usually you go to some place that is near " + noun1 + " or up on " + noun2 + ".")

then when I run the functions and provide input, it comes back with

 File "/Users/apple/Dropbox/MadLibs 6.py", line 52, in story
print("A vacation is when you take a trip to some " + adjective1 + " place with your "+ adjective2 + " family.")
NameError: name 'adjective1' is not defined

What does it mean by this, and how can I fix it?

3 Answers3

7

Its all about scope, you can not acces variable within another function scope Try this:

def userinput():
    adjective1 = input("Adjective: ")
    noun1 = input("Noun: ")
    noun2 = input("Noun: ")
    return adjective1, noun1, noun2

def story():
    adjective1, noun1, noun2 = userinput()
    print("A vacation is when you take a trip to some " + adjective1 + " place.")
    print("Usually you go to some place that is near " + noun1 + " or up on " + noun2 + ".")

By calling userinput on the second function and getting its returned info you can access it. Notice that adjective1, noun1 and noun2 form story function are locally scoped in that function so they are diferent from the userinput variables although they are named equally.

Netwave
  • 40,134
  • 6
  • 50
  • 93
0

Those variables are local to the function. This answer provides a good summary of the scoping in Python - Short Description of the Scoping Rules?.

You generally want to limit the available scope of variables as much as possible where practical, likely using function arguments in a case like this.

Community
  • 1
  • 1
Will Hogan
  • 909
  • 4
  • 9
0

Try this:

def userinput():
    global  adjective1
    adjective1 = input("Adjective: ")
    global noun1
    noun1 = input("Noun: ")
    global noun2
    noun2 = input("Noun: ")

def story():
    print("A vacation is when you take a trip to some " + adjective1 + " place.")
    print("Usually you go to some place that is near " + noun1 + " or up on " + noun2 + ".")
leela.fry
  • 283
  • 2
  • 3
  • 13
  • Its a posibility, but teaching this to someone that dont know how to handle scope is not a very good practice :) – Netwave Nov 08 '15 at 16:11
  • @DanielSanchez I find it practical and necessary when building games for example. – leela.fry Nov 08 '15 at 16:17
  • I've worked on a couple of titles and I think that declaring a global variable inside a function is not a good practice. Make them global by scopping them outside (and declaring global too if you require it). It's just my opinon, your code is another working option too :) – Netwave Nov 08 '15 at 16:23
  • I agree with you @DanielSanchez, however that script seems to look a bit like a game and that option may be good for it. – leela.fry Nov 08 '15 at 16:24