简体   繁体   中英

UnboundLocalError: local variable python

New to python and keep getting the error above when trying to run the below code. Could anyone be of assistance or provide guidance? thanks:)

def feature_4():
    flower_update = input("Enter the name of the flower you wish to change the price:"
                          "Lily, Rose, Tulip, Iris, Daisy, Orchid, Dahlia, Peony")
    flower_new_price = input("Enter the updated price of the flower")
    with open('flowers.txt') as amend_price:

        for line in amend_price:
            flower_price = int(line.split(',')[1])
            flower_name = str(line.split(',')[0])

    if flower_name == flower_update:
        flower_price.append(flower_new_price)
    print("The new price of", flower_update, "is", flower_new_price) 

You ran over a common problem, you cannot read a file and modify it at the same time. at least I have no idea how to do it and there are several options you can use to achieve your goals.

When writing with "w" flag, you will erase existing file. Thus you want to first read the file in memory, modifying it keeping it's data either in memory or in temporary files, then rewrite it.

I will skip the temporary file.

def feature_4(flower_file='flowers.txt'):

    flower_update = input("Enter the name of the flower you wish to change the price:"
                          "Lily, Rose, Tulip, Iris, Daisy, Orchid, Dahlia, Peony")
    flower_new_price = input("Enter the updated price of the flower")
    # here you should check that the input matches what you are expecting

    flower, price = [], []
    with open(flower_file) as amend_price:

        for line in amend_price:
            spt = line.strip().split(",")
            flower_price = int(spt[1])
            flower_name = str(spt[0])

            if flower_name == flower_update :
                price.append(flower_new_price)

            else:
                price.append(flower_price)

            flower.append(flower_name)

    with open(flower_file, "w") as f_:
        for i, v in enumerate(flower):
            f_.write("{},{}\n".format(v, str(price[i])))

    print("The new price of", flower_update, "is", flower_new_price) 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM