Не пишу первый вывод моего текста на python

откройте свою цель -> info -> измените «локальный регион разработки локализации» на ваш язык

1
задан Sara Tibbetts 4 March 2019 в 19:26
поделиться

1 ответ

Ваша программа делает то, что вы кодировали (если вы исправили ошибку IndentationError, скопированную в SO) - первое значение никогда не записывается в файл:

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

Измените его на:

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

Запишет хотя бы 1 цифру или текст в ваш файл.


Возможно, вы захотите прочитать Запрашивать у пользователя вводные данные, пока они не дадут действительный ответ , чтобы получить вдохновение, как избежать ValueErrors из int("some not numer").

Это Как отлаживать небольшие программы может помочь отладить ваши программы в будущем.

0
ответ дан Patrick Artner 4 March 2019 в 19:26
поделиться
Другие вопросы по тегам:

Похожие вопросы: