0

Im trying to save a variable so that when I run the script the le can be changed however I also want it to save the current value so that when I close the script and run it again, it should show the last value that was stored in that variable. Basically like a "score" variable.

I don't even know how to start because I have very limited knowledge about python.

import random
import time
import keyboard
import sys


token = 10
yourage = int(input("\033[1;36;40mWhat is your age?: "))
numbers = [1, 2, 3, 4, 5, 6]


def auth():
    if yourage >= 18:
        print("\nWelcome to the DIE GAME, Your objective is to try to guess the random generated number. If you manage to do so you will win 10 tokens, however if you lose you will lose 2 tokens. The numbers are between 1-6 \n")
        roll()
    else:
        print("You can not enter")
        return


def roll():
    global token
    while token == 0:
        print("You can no longer play!")
        sys.exit()
        return
    time.sleep(1.7)
    x = int(input("\033[1;36;40mEnter your guess: "))
    if x in numbers:
        print("The die is rolling...")
        time.sleep(2)
        temp = random.choice(numbers)
        print(temp)
        if temp == x:
            token = token + 10
            print("You guessed right! \n")
            print("\033[1;32;40mYour token amount is: ", token)
            print("\033[1;37;40m")
            again()
            return
        else:
            token = token - 2
            print("You guessed wrong :( \n")
            print("\033[1;31;40mYour token amount is: ", token)
            print("\033[1;37;40m")
            again()
    else:
        print("Your number must be between 1-6, try again")
        roll()


def again():
    roll()

What Im expecting is that the variable "Token" should save the value of it after the script and when running it in a new window it should show the last value before exiting the script instead of "10".

fodakall
  • 45
  • 6
  • 5
    Write the value to a file, read the value back from the file. You can't permanently store things in "variables". – deceze Sep 04 '19 at 10:32
  • I don't think that'd be possible in any language. – Diptangsu Goswami Sep 04 '19 at 10:36
  • I know that variables cant store values permanently I just know that there has to be another way for example setting a file and storing it into that file. But now I know that I can use sqlite3 module to create a database (pretty small one). – fodakall Sep 04 '19 at 10:40

1 Answers1

0
import os 

# Insert code at beginning of script to load score from backup
dir_path = 'C:/Desktop/'
back_up = os.path.join(dir_path, 'backup.txt')

if os.path.isfile(back_up):
    with open(back_up, 'r') as r:
        score = r.read()
else:
    score = open(back_up, 'w+')


# Insert code at end of script to save score to backup
with open(back_up, 'w') as w:
    w.write(score)
AnswerSeeker
  • 288
  • 1
  • 10