简体   繁体   中英

Writing numbers to file python. First input doesn't print

i'm writing numbers to a text file and it works but the issue im having is that it doesn't print the first number.

If I writing 1 2 3 4 5 6 then I have a sentinel loop and use -1 to end.

It would print 2 3 4 5 6

outfile = open("userInput.txt","w")
userInput = int(input("Enter a number to the text file: "))
count = 0
if int(userInput) != -1:
   while(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")
count+=1
outfile.close()

You are prompting the user a second time before you write the first input to the file.

See here: (I also simplified your code a little)

outfile = open("userInput.txt","w")
userInput = int(input("Enter a number to the text file: "))
count = 0
while(userInput !=-1): # You don't need the if, because if userInput == -1, this while loop won't run at all
   outfile.write(str(userInput) + "\n") # Swapped these lines so that it would write before asking the user again
   userInput = int(input("Enter a number to the text file: "))
   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()

You're asking for new input and writing that before you write the first valid input to the file. Instead, write the valid input first and then ask for input.

outfile = open("userInput.txt","w")
userInput = int(input("Enter a number to the text file: "))
count = 0
while(userInput != -1)
    outfile.write(str(userInput) + "\n")
    userInput = int(input("Enter a number to the text file: "))
    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()

This should work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM