-2

For some reason my code assigns the variables but then they change to their original value. (And I don't get any errors)

And the only time I change them is in check_database() I would really appreciate anyone who comments on this post.

CarNumbers = [
    {"number":"ABC 123", "oil":"10"},
    {"number":"ABC 124", "oil":"11"},
    {"number":"ABC 125", "oil":"12"}
]

IsValidCarNumber = False;
#this variable doesent work
TemporaryCarNumber = "";
#and this variable doesn't work too
TemporaryCarOil = 1;

def check_database(msg):
    for i in CarNumbers:
        if i["number"] == msg:
            #here I assign them
            TemporaryCarNumber = i["number"]
            TemporaryCarOil = i["oil"]
            return True
    return False



def make_reply(msg, validNumber):
    reply = None
    if msg is not None:
        if validNumber:
            #and here the variable doesn't work
            reply = "valid number!! Number:" + str(TemporaryCarNumber) + ", Oil:" + str(TemporaryCarOil)
        else:
            reply = "not valid number!"
        validNumber = False;
    return reply

update_id = None
while True:
    updates = bot.get_updates(offset=update_id)
    updates = updates["result"]
    if updates:
        for item in updates:
            update_id = item["update_id"]
            try:
                message = str(item["message"]["text"])
            except:
                message = None
            from_ = item["message"]["from"]["id"]
            valid = check_database(message)
            reply = make_reply(message, valid)
            bot.send_message(reply, from_)
  • 2
    Does this answer your question? [Use of "global" keyword in Python](https://stackoverflow.com/questions/4693120/use-of-global-keyword-in-python) – Kemp Aug 03 '21 at 13:23

1 Answers1

0

If you're changing the values of global variables (that means variables declared outside of the function) you need the global keyword

a = 0

def does_not_change():
    a = 1

def change():
    global a
    a = 1

print(a)
does_not_change()
print(a)
change()
print(a)
Achille G
  • 748
  • 6
  • 19