1

I am writing a series of numbers to a text file using a sentinel. If the user enters -1 it will end the program. I added in another loop for an if statement, and it is causing the first input the user makes to not print.

I could input: 1,2,3,4,5,-1

The text file would read: 2,3,4,5,-1

Here is my code:

outfile = open("userInput.txt","w")
userInput = int(input("Enter a number to the text file: "))
count = 0
while int(userInput) != -1:
   userInput = int(input("Enter a number to the text file: "))
outfile.write(str(userInput) + "\n")
count +=1
if(count) == 0:
   print("There is no numbers in the text file")
   outfile.write("There is no numbers in the text file")
outfile.close()

The while loop worked fine. When I made the count variable, count+=1, and the if statement then the writing problem occurred.

I made it so that if the user just enters no values it would say there's nothing in the text file and writes it to the file as well.

Sara Fuerst
  • 5,688
  • 8
  • 43
  • 86
l.m
  • 131
  • 1
  • 10
  • Your indendation is wrong. The "while" loop is going to be defined by the lines that are indented under the "while" statement. If that's as it's shown here, you should be getting errors. – mauve Mar 04 '19 at 19:15
  • @mauve Thank you for telling me hold on im redoing it, when i edited the program i thought it was identical – l.m Mar 04 '19 at 19:17
  • @mauve just changed it, when i copied my code it changed the indentation – l.m Mar 04 '19 at 19:18

1 Answers1

1

Your program does what you coded (if you fix the IndentationError cased by copying your code to SO) - the first value is never written to the file:

outfile = open("userInput.txt","w")
userInput = int(input("Enter a number to the text file: "))     # THIS is the first input
count = 0
while int(userInput) != -1:
   userInput = int(input("Enter a number to the text file: "))  # second to last input
   outfile.write(str(userInput) + "\n")                         # here you write it
   count +=1
if(count) == 0:
   print("There is no numbers in the text file")
   outfile.write("There is no numbers in the text file")
outfile.close()

Change it to:

count = 0
userInput = 99  # different from -1
with open ("userInput.txt","w") as outfile:
    while userInput != -1:
        userInput = int(input("Enter a number to the text file: "))
        if userInput != -1:
            outfile.write(str(userInput) + "\n") 
        else:
            outfile.write("There is no numbers in the text file\n") 

        count +=1

print("Done")

Will write at least 1 number or the text to your file.


You might want to read Asking the user for input until they give a valid response to get inspiration how to avoid ValueErrors from int("some not numer").

This How to debug small programs might help you debugyour programs in the future.

Patrick Artner
  • 50,409
  • 9
  • 43
  • 69