Random number file writer – In this lesson we will develop a simple algorithm for adding a random number to a file in Python.
Suppose we have a file that contains a number.
First we print the number contained in the file, then we generate a random number and add it to the number contained in the file.
Then we add the two numbers and add the resulting number to the file, starting with a new line.
Assuming the number_random.txt file contains the number 6, let’s try this example code:
import random
f = open('number_random.txt', 'r +')
number = f.readline()
print(number)
random_number = random.randint(1, 100)
print(random_number)
sum = random_number + int(number)
print(sum)
f.write('\ n' + str(sum))
f.close()
You must use the r + mode to be able to open a file for reading and writing at the same time.
Also remember that the write() method wants a string, so we need to convert the number obtained from reading the file into a string using casting with str().
Random number file writer – second example
In this second example we will try to guess the number that is contained in the number.txt text file.
Assuming the file contains only one number, we open the file in read-only mode and read the number. Then we ask what the number contained in the file is and give a victory or defeat message after comparing it.
Let’s develop a possible algorithm that solves our problem using also a simple function:
f = open('number.txt', 'r')
number = f.readline()
def guess(num):
if num == number:
return True
my_number = input('What number is contained in the file ?:')
result = guess(my_number)
if result:
print('You guessed it!')
else:
print('You didn't guess')
print('The number was:' + number)
f.close()
Random number file writer – third example
Now let’s modify the algorithm giving help to the user. Each time the user tries to guess, he will be told if the number thought is lower or higher than the one contained in the text file.
All for 5 times.
When we are faced with a complex problem we have to break it down into subproblems to make it easier.
So let’s first develop the simplest case, i.e. just one answer:
f = open('number.txt', 'r')
number = f.readline()
def guess(num):
if num == number:
return 0
elif num > number:
return 1
else:
return 2
my_number = input('What number is contained in the file ?:')
result = guess(my_number)
if result == 0:
print('You guessed it!')
elif result == 1:
print('The number to guess is lower')
else:
print('The number to guess is higher')
f.close()
Now we generate the 5 attempts, making sure to end the game when the attempts are finished or when you guess.
We generate a first solution in which we will exit the cycle through the use of break:
f = open('number.txt', 'r')
number = f.readline()
def guess(num):
if num == number:
return 0
elif num > number:
return 1
else:
return 2
attempts = 5
for i in range(attempts):
my_number = input('What number is contained in the file ?:')
result = guess(my_number)
if result == 0:
print('You guessed it!')
break
elif result == 1:
print('The number to guess is lower')
else:
print('The number to guess is higher')
f.close()
Now let’s create a new function thus avoiding the use of the break:
f = open('number.txt', 'r')
number = f.readline()
def guess(num):
if num == number:
return 0
elif num > number:
return 1
else:
return 2
attempts = 5
found = False
def game():
for i in range(attempts):
my_number = input('What number is contained in the file ?:')
result = guess(my_number)
if result == 0:
print('You guessed it!')
return
elif result == 1:
print('The number to guess is lower')
else:
print('The number to guess is higher')
game()
f.close()
In this lesson we have developed some algorithms such as adding a random number in a file in Python, or guessing the number contained in a text file. In the next few lessons we will practice the files again.
Some useful links
Introduction to dictionaries in Python
Use Python dictionaries
Create dictionaries in Python
Python get() method
keys() method
items() method
pop() method
popitem() method
Sort dictionary in Python