Store numbers in a file

Hi! I want to create a programme that ask numbers, it stores them in a file and that when the user gives the number 0 the programme stops. I’ve created the following programme but it does not stop when 0 and it stores nothing in the file. Where is the mistake?

file=open(“file.txt”, “w”)
while True:
n=input(“enter a number:”)
file.write(n);
if n==0:
file.close()
print(file)
break

The input() function always returns a string, so n is a string in your code. Because 0 is not a string, n will never be equal to 0. To read an integer input from the console, you can do something like n = int(input("Enter an integer:")), since the int() function converts a string of digits to an integer.

Dennis,

You are right that Izan can convert the string to an int, but having
done that, Izan has to immediately convert it back to a string in order
to write it to a file.

Hi Izan,

As Dennis has already explained, you are comparing the int 0 with the
string ‘0’, which never compares as equal, so the loop never breaks.

Instead, you should use if n == "0".

Also, print(file) doesn’t do what you seem to think it does. It will
print something like:

<_io.TextIOWrapper name='file.txt' mode='w' encoding='UTF-8'>

If you want to see the contents of the file, you need to close it (as
you have already done), then reopen it using ‘r’ (read) mode, and read
the file back.

When you do that, you will see that you have forgotten something small
but critical when writing the numbers to the file :slight_smile:

(Hint: if you write the three numbers 12 358 and 9 into the file, what
do you get when you read the file back?)

1 Like