Kryptic Coding

APPS, TUTORIALS, GAMES AND MORE!

PYTHON FILES

Tutorial By Kryptic Coding

What we will be doing:

In this tutorial we will be learning how to read from and write to files in Python, as well as learning how to use the random module. For this tutorial I will be running Python 3. If you dont have Python you can get it here.

In order to learn how to do these things, we will make a coin flip program. To start off make a file called balance.txt. For now we will leave this file blank.
Now we will make our Python file, which you can call whatever you want. Once done you are ready to begin coding!

To start off we are going to add import random to the top of our code so later on we can use it to do the flipping. Next we will write a function that will get the current balance from balance.txt.


def getBalance():
	with open('balance.txt', 'r') as file: #Means that we now reference the open balance.txt as file. The 'r' means we are reading from the file
		balance = float(file.read()) #Gets the contents of the file, then converts to number
		file.close() #Closes the file
		return balance
	

To test if our function is working correctly, put 10 into balance.txt and if you add print(getBalance()) to your program and if working correctly it should print out 10.0. You can remove this after testing if you wish.

Now we will write a function to put a balance back into balance.txt.


def writeBalance(balance):
	with open('balance.txt', 'w') as file: #Means that we now reference the open balance.txt as file. The 'w' means we are writing to the file
		file.write(str(balance)) #Writes the balance into the file - makes sure it is a string as it will not accept a number
		file.close() #Closes the file
	

As it is important to test each bit of code you write as you write it we are going to test this as well. To do this we are going to add the following to our code:


bal = getBalance()
print(bal)
writeBalance(bal * 2)
print(getBalance())
	

If working correctly the program should print out the starting balance and then that balance doubled. Once again you can remove this if you want.

Finally we need to add the coin flipping section of the code which will make use of the functions we have already created.

This part of the code needs to do a few things. It will need to get input from the user about the betting amount and which side of the coin they want to bet on. After this it will need to decide what the result of the flip was, and then based on that write to the file the new balance. We are going to put this in a while loop so the program will run until the user types quit.


flipValues = {'T': 0, 'H': 1} #Sets a dictionary for easy if statement later on
bal = getBalance()
print('Current balance: ' + str(bal))

userBet = float(input('Bet amount: ')) #Gets input and converts to number
while userBet > bal: #Makes sure bet is not more than current balance
    print('Bet too high, please enter an amount <= ' + str(bal))
    userBet = float(input('Bet amount: ')) #Gets input and converts to number
userChoice = input('H or T? ')
while userChoice != 'quit': #Exits the program if the user types quit
    flip = random.randint(0, 1) #Returns either 0 or 1
    if flipValues[userChoice] == flip: #Checks if the flip equals what is in the dictionary for user choice
        bal += userBet
        print('You Won!')
    else:
        bal -= userBet
        print('You Lost')
    writeBalance(bal)
    bal = getBalance()
    print('Current balance: ' + str(bal))
    userBet = float(input('Bet amount: ')) #Gets input and converts to number
    while userBet > bal: #Makes sure bet is not more than current balance
        print('Bet too high, please enter an amount <= ' + str(bal))
        userBet = float(input('Bet amount: ')) #Gets input and converts to number
    userChoice = input('H or T? ')    
	

If you want you can download the .py program from this tutorial using the button below (you can make your own balance.txt).

Extension ideas:

Feeling like more of a challenge? Here are some ideas for you to add onto this program:

Conclusion:

Learning what you did in this tutorial will help with lots of things throughout your programming career. Reading and writing to files is neccessary in lots of cases - sometimes it might be data that is being given to you in a file, other times it might be saving progress in games. Lastly, if you had any issues with this tutorial please contact us!


Contact