-3

Consider the following code (I received a name error when running this)

item = input("What food???")
def itemcheck():
    if item == "chex":
        cereal = "Yummy"
    else:
        cereal = "Yuck!"

itemcheck()
print(cereal)

the error was name 'cereal' is not defined. What error am I making/how do I fix it? What is the correct way to define a variable in your own function?

  • You just called `itemcheck()` but you are not returning anything from the function back to where it was called from. In your case, you should `return cereal` – Sheldore Sep 20 '18 at 16:41

4 Answers4

1

Your code should be more optimized. You can try this:

def itemcheck():
    if item == "chex":
        return "Yummy"
    else:
        return "Yuck!"
item = input("What food???")
cereal = itemcheck()
print(cereal)

You're defining cereal inside of function, not in a global scope. That's why you're unable to access cereal outside of the function.

Taohidul Islam
  • 5,246
  • 3
  • 26
  • 39
1

Using a Global variable

A variable which is defined inside a function is local to that function. However, if you declare it as a global variable, it becomes accessible outside the function.

item = input("What food???")
def itemcheck():
    global cereal
    if item == "chex":
        cereal = "Yummy"
    else:
        cereal = "Yuck!"

itemcheck()
print(cereal)

.

Using a return statement

You could make a return statement, which specifies the value to be passed back to the code that called the function.

item = input("What food???")
def itemcheck():
    if item == "chex":
        return "Yummy"
    else:
        return "Yuck!"

print(itemcheck())
0
item = input("What food???")
def itemcheck():
    if item == "chex":
        cereal = "Yummy"
    else:
        cereal = "Yuck!"
    return cereal

cereal = itemcheck()
print(cereal)

You did not return cereal from the function. Since cereal was declared in the function, unless you return it from the function, it doesn't exist after the function has completed it's call. So you need to return it before the function exits.

Atul Shanbhag
  • 636
  • 5
  • 13
  • While providing the correct code is good, it would be very helpful if you could also describe in words what the original problem was and how it was fixed. – G. Sliepen Sep 20 '18 at 18:26
0
def itemcheck():
    item = input("What food???")
    cereal = item
    if item == "chex":
        cereal = "Yummy"
    else:
        cereal = "Yuck!"
    print(cereal)

itemcheck()
Brndn
  • 676
  • 1
  • 7
  • 21