Запись чисел в файл python.Первый ввод не печатается - PullRequest
0 голосов
/ 07 марта 2019

Я пишу числа в текстовый файл, и это работает, но проблема в том, что он не печатает первое число.

Если я пишу 1 2 3 4 5 6, тогда у меня естьсторожевой цикл и используйте -1 до конца.

Будет напечатано 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()

Ответы [ 2 ]

1 голос
/ 07 марта 2019

Вы запрашиваете новый ввод и записываете его перед тем, как записать первый действительный ввод в файл. Вместо этого сначала напишите правильный ввод, а затем запросите ввод.

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()

Это должно работать.

1 голос
/ 07 марта 2019

Вы запрашиваете пользователя во второй раз, прежде чем записать первый ввод в файл.

См. Здесь: (Я также немного упростил ваш код)

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()
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...