I cannot add "variable = variable + 1" to the while loop

Asked

Viewed 60 times

-2

I have the following code:

quantidade = int(input("Quantos episódios? "))
inicio = 1
numero_do_post = 379
numero_do_anime = 6
arquivo = open("script.txt", "w")

while (inicio <= quantidade):
    arquivo.write(numero_do_anime)
    inicio = inicio + 1
arquivo.close()

When I print the variable it gives the following error:

Traceback (most recent call last):
  File ".\script.py", line 11, in <module>
    arquivo.write(numero_do_anime)
TypeError: write() argument must be str, not int

I want him to come out a number in a row: 6,7,8 etc... do not understand the mistake.

  • The problem is not in the inicio = inicio + 1, but in the arquivo.write. The error message is saying: the function write accepted only string as parameter and you are passing an integer.

  • So how can I write the number in the text, so that in the next loop it gets itself + 1?

  • What exactly do you want to do? If you just fix the question error you will write in your file several times the number 379. For example, if the user typed 100 in his file they would have 100 times the number 379. It doesn’t seem like that’s what you want, so just solving the problem wouldn’t be enough. Could you describe in detail what you are trying to do and what output you want?

2 answers

4

When you open a file with open() it returns an object of the type file object.

From it you can write in the file doing meu_arquivo.write(conteudo) where content should be a string.

So, if your data is not a string it will result in an error, as in your case, where you try to write whole in the file.

To get around you must convert data type before writing with something like:

       arquivo.write(str(numero_do_anime))
  • So... This I get... Problem is I want to put 6, 7, 8, 9... Not the same number several times understood... That’s my problem...

  • In your code you have write in the file numero_do_anime but does not update the value of the veritable. Therefore, you have the same value always being written in the file.

0

I corrected... it was a very silly thing actually...

I had already done before what BXL had said. But in my case I had only put right after the arquivo.write(str(numero_do_anime))... the code: numero_do_anime = numero_do_anime + 1

Browser other questions tagged

You are not signed in. Login or sign up in order to post.