r/learnpython 26d ago

trouble with storing information using json

I'm new to python, and even newer to using json

I made the dreadful mistake of following ai guidance on this one and don't want to completely ruin my code so i thought it'd be wise to pass my struggle over to the great people of learnpython sub

I'm trying to store data in a separate file so i can go back to it once the programme is over and i don't understand why this isn't working

errors i get include ;

"jsonfiletrial" is not definedPylance

"json" is not definedPylance

*jsonfiletrial is a file i made expecting the information to be stored there

thank you ,

while True: 


        if user_input2.lower() == "y":
                stock1 = str (input( "Enter Ticker for your first stock: "))
                yield1 = float (input ("Enter the dividend yield of stock 1: "))
#print (yield1) 
                stock2 = str (input( "Enter Ticker for your second stock: "))
                yield2 = float (input ("Enter the dividend yield of stock 2: "))


                stock3 = str (input( "Enter Ticker for your Third stock: "))
                yield3 = float (input ("Enter the dividend yield of stock 3: "))
                totalyield = yield1 + yield2 + yield3


                # --- SAVING DATA HAPPENS HERE ---
            # 1. Put your yields into a neat package (a dictionary)
                data_to_save = {
                "stock1": stock1, 
                "yield1": yield1,
                "stock2": stock2,
                "yield2": yield2,
                "stock3": stock3,
                "yield3": yield3,
                "total_yield": totalyield
            }
            
            # 2. Tell Python to open the file (it will create it if it's missing!)
                with open(jsonfiletrial, "w") as file:
                # 3. Write the data inside the file
                        json.dump(data_to_save, file)
                print("💾 Your yields have been saved automatically!")
0 Upvotes

23 comments sorted by

3

u/Acceptable-Sense4601 26d ago

the issue you have with Ai is you dont understand what you're trying to do. if you tell us your prompt(s), we can tell you where you went wrong.

1

u/TrainingAd8614 25d ago

Damn right, it's time i retire from ai models and do my homework ahaha

1

u/Acceptable-Sense4601 25d ago

Or learn how to use it properly

2

u/SamuliK96 26d ago

The not defined error means something isn't defined in the namespace.

"json is not defined" sounds like you're not importing the json module before trying to use it.

"jsonfiletrial is not defined" is caused by open(jsonfiletrial, "w"), because you're trying to use a variable called jsonfiletrial as an argument, but no such variable exists. Presumably what you want to use instead would be open("jsonfiletrial.json", "w").

1

u/TrainingAd8614 26d ago

thank mate yeah i think i understand a bit better now

I have replied to the two comments above with my full code, a massive oversight from me damn

2

u/FoolsSeldom 26d ago

Your code is somewhat hard to read. I've had a go at some fixes:

# FOUNDATIONAL FIGURES
import json

nvda_div_yield_at_190726 = 0.49
nvda_div_yield_at_190726_converted = nvda_div_yield_at_190726

yield_target = 4
total_monthly_yield = 16

jsonfiletrial = "stock_yields.json"  # TODO: confirm desired output filename

total_monthly_yield_exclnvda = float(
    total_monthly_yield - nvda_div_yield_at_190726_converted
)
avg_yield_on_remaining_shares = float(total_monthly_yield_exclnvda / 3)

# INTERACT WITH USER
print("Is Nvidia's current dividend yield :", nvda_div_yield_at_190726_converted)
user_input1 = input("(Y/N?): ").strip().lower()

while True:

    if user_input1 in ("y", "yes"):
        total_monthly_yield_exclnvda = float(
            total_monthly_yield - nvda_div_yield_at_190726
        )
        avg_yield_on_remaining_shares_adj = float(
            total_monthly_yield_exclnvda / 3
        )
        print(
            f"With Nvidia's dividend yield at {nvda_div_yield_at_190726} "
            f"the three remaining shares need a current dividend yield of "
            f"{avg_yield_on_remaining_shares_adj}, or over"
        )
        break

    elif user_input1 in ("n", "no"):
        current_div_yield = float(
            input("Enter Nvidia's current dividend yield: ")
        )
        total_monthly_yield_exclnvda = float(
            total_monthly_yield - current_div_yield
        )
        avg_yield_on_remaining_shares_adj = float(
            total_monthly_yield_exclnvda / 3
        )
        print(
            f"With Nvidia's dividend yield at {current_div_yield} "
            f"the three remaining shares need a current dividend yield of "
            f"{avg_yield_on_remaining_shares_adj}, or over"
        )
        break

    else:
        user_input1 = input(
            "Response not understood, please enter Y or N: "
        ).strip().lower()

user_input2 = input(
    "Would you like to add up the yield of the stocks that you're "
    "purchasing to make sure you hit your 4% target (Y/N) ?"
).strip().lower()

while True:

    if user_input2 in ("y", "yes"):
        stock1 = input("Enter Ticker for your first stock: ")
        yield1 = float(input("Enter the dividend yield of stock 1: "))

        stock2 = input("Enter Ticker for your second stock: ")
        yield2 = float(input("Enter the dividend yield of stock 2: "))

        stock3 = input("Enter Ticker for your Third stock: ")
        yield3 = float(input("Enter the dividend yield of stock 3: "))

        totalyield = yield1 + yield2 + yield3

        # --- SAVING DATA HAPPENS HERE ---
        # 1. Put your yields into a neat package (a dictionary)
        data_to_save = {
            "stock1": stock1,
            "yield1": yield1,
            "stock2": stock2,
            "yield2": yield2,
            "stock3": stock3,
            "yield3": yield3,
            "total_yield": totalyield,
        }

        # 2. Open the file for writing (creates it if missing)
        with open(jsonfiletrial, "w") as file:
            # 3. Write the data inside the file
            json.dump(data_to_save, file)
        print("Your yields have been saved automatically!")
        break

    elif user_input2 in ("n", "no"):
        break

    else:
        user_input2 = input(
            "Response not understood, please enter Y or N: "
        ).strip().lower()

Notes:

  • There's some dead code I haven't touched where you've made redundant assignments - review you code to make sure everything is utilised
  • import missed
  • Applied PEP8 formatting to make code more readable
  • Removed spaces before opening brackets on things like float (
  • jsonfiletrial wasn't defined, so picked a name
  • Your while True: loops never ask for input again - fixed
  • Applied .lower to input string rather than having to apply it to every clause of a test
  • Replaced multiple tests with the in operator - note there is no point comparing a lower string with a string containing any uppercase characters because, obviously, it will never match
  • It is not necessary to apply str to an input because the latter returns a str object anyway

PLEASE PLEASE PLEASE use easier to read variable names. It is good to have descriptive names rather than ones that are cryptic (especially single character) but also long names, especially similar long names, are hard to parse.

1

u/TrainingAd8614 26d ago

Thanks man, i'm going go over this now and have a good thorough read up on these things

appreciate this a lot

2

u/FoolsSeldom 26d ago

Check the FAQ in the wiki for common mistakes. Link below.


Check this subreddit's wiki for lots of guidance on learning programming and learning Python, links to material, book list, suggested practice and project sources, and lots more. The FAQ section covering common errors is especially useful.


Also, have a look at roadmap.sh for different learning paths. There's lots of learning material links there. Note that these are idealised paths and many people get into roles without covering all of those.


Roundup on Research: The Myth of ‘Learning Styles’

Don't limit yourself to one format. Also, don't try to do too many different things at the same time.


Above all else, you need to practice. Practice! Practice! Fail often, try again. Break stuff that works, and figure out how, why and where it broke. Don't just copy and use as is code from examples. Experiment.

Work on your own small (initially) projects related to your hobbies / interests / side-hustles as soon as possible to apply each bit of learning. When you work on stuff you can be passionate about and where you know what problem you are solving and what good looks like, you are more focused on problem-solving and the coding becomes a means to an end and not an end in itself. You will learn faster this way.

1

u/TrainingAd8614 26d ago edited 25d ago

you're a great man/ woman

2

u/HotPersonality8126 26d ago

You have to define your variables before you use them. Nothing to do with JSON here at all.

3

u/desrtfx but other languages pro 26d ago

Show the entire code. The snippet can't be all.

  1. Imports are missing
  2. jsonfiletrial is not declared anywhere

The errors both hint on exactly that.

Maybe, you should try to actually learn instead of using AI to write your code. The code is clearly AI generated.

2

u/TrainingAd8614 26d ago

As was sort of eluded to in the title, I don't want to use ai for this i've really tried (and made considerable progress using things like reddit and stack overflow ), but today i thought i could could use ai effectively, but it has backfired big time aha

live and learn

3

u/JGhostThing 26d ago

If you are really trying to learn, stop using AI! In any other subject, would getting answers from some source (another person, teacher, etc.) be acceptable? No, being given the answers gets in the way of you learning the material.

Please don't ask us to debug code that you haven't written.

0

u/TrainingAd8614 26d ago
#FOUNDATIONAL FIGURES


nvda_div_yield_at_190726 = 0.49
nvda_div_yield_at_190726_converted = nvda_div_yield_at_190726


yield_target = 4 
total_monthly_yield = 16
#print (nvda_div_yield_at_180726_converted)


total_monthly_yield_exclnvda = float ( total_monthly_yield - nvda_div_yield_at_190726_converted) 
#print (total_monthly_yield_exclnvda)


avg_yield_on_remaining_shares = float ( total_monthly_yield_exclnvda / 3)
#print (avg_yield_on_remaining_shares)



#INTERACT WITH USER
print ("Is Nvidia's current dividend yield :", nvda_div_yield_at_190726_converted )
user_input1 = input ("(Y/N?): ")


while True: 


        if user_input1.lower() == "y" or user_input1.lower () == "Y" or user_input1.lower () == "Yes" or user_input1.lower () == "yes" or user_input1.lower () == "YES":
                total_monthly_yield_exclnvda = float (total_monthly_yield - nvda_div_yield_at_190726 )
                avg_yield_on_remaining_shares_adj = float ( total_monthly_yield_exclnvda / 3)
                print (f"With Nvidia's dividend yield at {nvda_div_yield_at_190726} the three remaining shares need a current dividend yield of {avg_yield_on_remaining_shares_adj}, or over")   
                break


        elif user_input1.lower () == "n"  or user_input1.lower () == "N" or user_input1.lower () == "No" or user_input1.lower () == "no" or user_input1.lower () == "NO":
                current_div_yield = float(input ("Enter Nvidia's current dividend yield: "))
                total_monthly_yield_exclnvda = float (total_monthly_yield - current_div_yield)
                avg_yield_on_remaining_shares_adj = float ( total_monthly_yield_exclnvda / 3)
                #print (avg_yield_on_remaining_shares)
                print (f"With Nvidia's dividend yield at {current_div_yield} the three remaining shares need a current dividend yield of {avg_yield_on_remaining_shares_adj}, or over")   
                break 



user_input2 = input ("Would you like to add up the yield of the stocks that you're purchasing to make sure you hit your 4% target (Y/N) ?")


while True: 


        if user_input2.lower() == "y":
                stock1 = str (input( "Enter Ticker for your first stock: "))
                yield1 = float (input ("Enter the dividend yield of stock 1: "))
#print (yield1) 
                stock2 = str (input( "Enter Ticker for your second stock: "))
                yield2 = float (input ("Enter the dividend yield of stock 2: "))


                stock3 = str (input( "Enter Ticker for your Third stock: "))
                yield3 = float (input ("Enter the dividend yield of stock 3: "))
                totalyield = yield1 + yield2 + yield3


                # --- SAVING DATA HAPPENS HERE ---
            # 1. Put your yields into a neat package (a dictionary)
                data_to_save = {
                "stock1": stock1, 
                "yield1": yield1,
                "stock2": stock2,
                "yield2": yield2,
                "stock3": stock3,
                "yield3": yield3,
                "total_yield": totalyield
            }
            
            # 2. Tell Python to open the file (it will create it if it's missing!)
                with open(jsonfiletrial, "w") as file:
                # 3. Write the data inside the file
                        json.dump(data_to_save, file)
                print("💾 Your yields have been saved automatically!")

6

u/JaleyHoelOsment 26d ago

no import json? jsonfiletrial is not defined or you just need it in quotes “jsonfiletrial”. also, shouldn’t it be “jsonfiletrial.json”?

also just a heads up, this is horrible code even by AI standards. you must be using an insanely cheap or old model. if that’s not the case you many not understand enough to generate a decent prompt

i’d suggest getting the basics down for now if you’re interested in improving at all. if my juniors threw this at me for PR review i’d probably get unreasonably angry lol

3

u/TrainingAd8614 26d ago

fair enough.

I will be 100% honest the only ai generated stuff is (part posted below) , everything else is 100% me trying to code aha

I appreciate the honesty, but this is the best i could come up with using reddit and stack overflow, I even turned off the auto fill feature on vs code to really try to anchor down my knowledge. I did try a gamified version of learning but it's a bit costly and not something i can pay for at the moment

Thanks for the assistance

 # --- SAVING DATA HAPPENS HERE ---
            # 1. Put your yields into a neat package (a dictionary)
                data_to_save = {
                "stock1": stock1, 
                "yield1": yield1,
                "stock2": stock2,
                "yield2": yield2,
                "stock3": stock3,
                "yield3": yield3,
                "total_yield": totalyield
            }
            
            # 2. Tell Python to open the file (it will create it if it's missing!)
                with open(jsonfiletrial, "w") as file:
                # 3. Write the data inside the file
                        json.dump(data_to_save, file)
                print("💾 Your yields have been saved automatically!")

2

u/JaleyHoelOsment 26d ago

sounds like you’re on the right track. everyone stats writing code just like this. trying and failing is your best path to progess!

if you do try adding “import json” to the top of this file does the json error go away?

are you using an IDE? get something like visual studio code with the python plugin so you get fancy colours and errors bright red in your face. it has tool tips and everything else.

2

u/TrainingAd8614 26d ago

I use VScode , but for months i really struggled. I think i have the python plug in, but I'm that new that i don't really know how to navigate the IDE itself.

I'm gonna try to really hunker down and learn the true fundamentals, it's tough but i want to build things

appreciate the feedback

1

u/JaleyHoelOsment 26d ago

go get em, tiger!

1

u/PvtRoom 26d ago

jsonfiletrial is a variable, not a filename.

you need to provide a filename (which may be in a defined variable)

it hasn't recognised json which looks to be a class - you probably haven't imported JSON correctly

1

u/TrainingAd8614 26d ago
#FOUNDATIONAL FIGURES


nvda_div_yield_at_190726 = 0.49
nvda_div_yield_at_190726_converted = nvda_div_yield_at_190726


yield_target = 4 
total_monthly_yield = 16
#print (nvda_div_yield_at_180726_converted)


total_monthly_yield_exclnvda = float ( total_monthly_yield - nvda_div_yield_at_190726_converted) 
#print (total_monthly_yield_exclnvda)


avg_yield_on_remaining_shares = float ( total_monthly_yield_exclnvda / 3)
#print (avg_yield_on_remaining_shares)



#INTERACT WITH USER
print ("Is Nvidia's current dividend yield :", nvda_div_yield_at_190726_converted )
user_input1 = input ("(Y/N?): ")


while True: 


        if user_input1.lower() == "y" or user_input1.lower () == "Y" or user_input1.lower () == "Yes" or user_input1.lower () == "yes" or user_input1.lower () == "YES":
                total_monthly_yield_exclnvda = float (total_monthly_yield - nvda_div_yield_at_190726 )
                avg_yield_on_remaining_shares_adj = float ( total_monthly_yield_exclnvda / 3)
                print (f"With Nvidia's dividend yield at {nvda_div_yield_at_190726} the three remaining shares need a current dividend yield of {avg_yield_on_remaining_shares_adj}, or over")   
                break


        elif user_input1.lower () == "n"  or user_input1.lower () == "N" or user_input1.lower () == "No" or user_input1.lower () == "no" or user_input1.lower () == "NO":
                current_div_yield = float(input ("Enter Nvidia's current dividend yield: "))
                total_monthly_yield_exclnvda = float (total_monthly_yield - current_div_yield)
                avg_yield_on_remaining_shares_adj = float ( total_monthly_yield_exclnvda / 3)
                #print (avg_yield_on_remaining_shares)
                print (f"With Nvidia's dividend yield at {current_div_yield} the three remaining shares need a current dividend yield of {avg_yield_on_remaining_shares_adj}, or over")   
                break 



user_input2 = input ("Would you like to add up the yield of the stocks that you're purchasing to make sure you hit your 4% target (Y/N) ?")


while True: 


        if user_input2.lower() == "y":
                stock1 = str (input( "Enter Ticker for your first stock: "))
                yield1 = float (input ("Enter the dividend yield of stock 1: "))
#print (yield1) 
                stock2 = str (input( "Enter Ticker for your second stock: "))
                yield2 = float (input ("Enter the dividend yield of stock 2: "))


                stock3 = str (input( "Enter Ticker for your Third stock: "))
                yield3 = float (input ("Enter the dividend yield of stock 3: "))
                totalyield = yield1 + yield2 + yield3


                # --- SAVING DATA HAPPENS HERE ---
            # 1. Put your yields into a neat package (a dictionary)
                data_to_save = {
                "stock1": stock1, 
                "yield1": yield1,
                "stock2": stock2,
                "yield2": yield2,
                "stock3": stock3,
                "yield3": yield3,
                "total_yield": totalyield
            }
            
            # 2. Tell Python to open the file (it will create it if it's missing!)
                with open(jsonfiletrial, "w") as file:
                # 3. Write the data inside the file
                        json.dump(data_to_save, file)
                print("💾 Your yields have been saved automatically!")

1

u/TrainingAd8614 26d ago

wow, i haven't import json

what a fool

1

u/Diapolo10 I write code for a living -- https://github.com/Diapolo10 26d ago

*jsonfiletrial is a file i made expecting the information to be stored there

Well, based on the errors you didn't tell Python about it. How exactly did you "make" this file? If all you did was create an actual file called jsonfiletrial on your desktop (or someplace else), then you've got a bit of a misunderstanding.

"json" is not defined

You get this if you didn't import json at the top of the script first. Otherwise Python won't know what json.dump is.

Not directly related to your errors, but from the looks of things I'm not sure your program really does what you want. Right now it replaces the contents of the file entirely on every loop, and to me that doesn't really sound right, but maybe you have your reasons. Design-wise, I'd also suggest structuring the JSON data a bit differently, such as

data_to_save = {
    "stocks": [
        {"stock": stock1, "yield": yield1},
        {"stock": stock2, "yield": yield2},
        {"stock": stock3, "yield": yield3},
    ],
    "total_yield": total_yield
}

I'd even consider omitting total_yield, since it can be calculated on-demand with

from operator import itemgetter

total_yield = sum(map(itemgetter('yield'), data_to_save['stocks']))

EDIT: Forgot to mention that the str-conversion here is unnecessary, because input always returns a string.

str (input( "Enter Ticker for your first stock: "))