Confused as to why this code doesn’t work sometimes.

So I’m super beginner and working through a course using jupyter notebooks and having some issues with a fishstore assignment asking for inputs for fish name and price.

The code I originally used was

def fishstore(fish, price): fish = input("What kind of fish?").title() price = input("What is the price of the fish") return(fish + " costs $"+ price)

print(fishstore(fish, price))

And returns this error

NameError Traceback (most recent call last) <ipython-input-1-724725085cab> in <module> 4 return(fish + " costs $"+ price) 5 ----> 6 print(fishstore(fish, price))

NameError: name 'fish' is not defined

So I rearranged the code as follows

fish = input("What kind of fish?").title() price = input("What is the price of the fish") def fishstore(fish, price): return(fish + " costs $"+ price)

print(fishstore(fish, price))

Which worked. But now the real confusion begins. When I copy and paste the original code back into the notebook it suddenly works fine but never works in a new notebook. Meanwhile the latter code works fine in a new notebook and the original notebook. Can anyone explain this to me?

Posted Jan 25, 2021, 4:54 PM UTC · edited

15
TouchingTheVodka•

Which worked. But now the real confusion begins. When I copy and paste the original code back into the notebook it suddenly works fine but never works in a new notebook

The two variables you've defined remain in the state so your first function will now work.

2
SpacemanBatmanOP•

Gotcha thank you

1
crashfrog•

Can anyone explain this to me?

Notebooks retain state and the state is the interpreter's state, so it's shared between all cells. If cell 2 defines a name, then you can go back and use that name in cell 1 provided you executed cell 2 at least once. On the other hand, if you try to run cell 1 and then cell 2 on a new notebook or a just-restarted kernel, the name won't be defined in cell 1 yet and you'll get a NameError.

That does, in fact, make code notebooks a very confusing place to try to learn to write Python since at any time, the true state of the interpreter isn't obvious. That's why generally it's not recommended for Python students to work in code notebooks - if you don't know what you're doing, you get weird, inconsistent behavior because you're manipulating global state without knowing it.

1
SpacemanBatmanOP•

What’s a good place to work in as a beginner?

1
crashfrog•

Write Python in a text editor, save the file, run it at the command line. Since the interpreter terminates after every run, it never starts in an undetermined state, and you'll encounter problems "honestly", without them being covered up by unintentional hidden state.

1