Day 053 - Project 53 : My Inventory

i looked again at your code and made it run offline and it works.
So not sure here. For a second I thought you forgot to eval the file on read but I was wrong.

Do you get some exception error? I hope
This is not repl fault.

it’s an issue of the scope of variables. i don’t fully understand it yet, but subroutines can’t access global variables. since you’re defining ‘inventory’ in the main body, it’s a global variable. if you’re using the replit editor, it should show you this yellow squiggly line:

image

this tells you that the subroutines couldn’t access the global variable ‘inventory’, so it treats it as a local variable instead. this means any data read into this local variable will be unaccessible outside the subroutine unless it’s explicitly returned.

your code works if you load the global variable with ‘global’ (notice how the squiggly line disappeared):
image

however use of ‘global’ is considered a bad practice (apparently it can slow things down, among other things). so another way is to use a local variable inside the subroutine into which you load the file, then return that variable:
image
in the main loop assign that value to ‘inventory’
image
you’ll need to return an empty list from the except part too:
image

as to why the other subroutines can seemingly interact with global variables, i guess they don’t actually load it, but only send instructions what to do with it. in visual studio code you can see this when hovering over variables: even though ‘inventory’ is defined as a list, the subroutine doesn’t know this because it hasn’t loaded it:
image
whereas when hovering over inventory in the mainbody it is correctly identified as a list:
image
i haven’t properly studied the topic of scope yet, so i could be wrong on the details. but this issue has mystified me several times…

2 Likes

Inventory is global and this means you need to handle it as such in the procedures,
The best is to never use global variables and always pass them as arguments.

1 Like

Thanks! This really helped me a lot! :slight_smile:
But yeah, would be interesting to comprehend why the other subroutines had no problem accessing the global list.

2 Likes

It depends if they read or write and how. Just avoid globals and you will be fine for the rest of your programming life!

1 Like

https://replit.com/@arhanansari2009/RPG-Inventory-System?v=1
I have solved Day 53
see my code
P.S:Already completed Day 100

Everything except remove function works fine. I’m not getting the output expected. There are no error messages though. Please help.

Here’s a link to the repl : https://replit.com/@SUMAYDOHARE/Day53100Days

That is maybe because capitalise is not the same as upper …

2 Likes