How I write in Python documents on For

Asked

Viewed 52 times

0

arquivo = open('escala.txt', 'w') for i in range(0, 101): var = (i * 2000)/100 arquivo.white('Temperature is:',i ,'°C converted is:', var) arquivo2.close()

That’s not possible I’d like to know how to do it normally

Note: sorry I’m new here so I don’t know much about how to search and ask correctly

  • The . white there, right? wasn’t supposed to be . write? and in the end, archive2.close() was supposed to be.close file()

  • truth I’m sorry, it is possible to edit the publication?

  • 1

    .write takes a string, so vc will have to format, set Iver using python 3.6 or higher use fstring, f'Temperature is:{i} °C converted is: {var} n'

  • thanks for the tip!

2 answers

1

There are some things wrong with your script, but I think what you want to do is this:

arquivo = open('escala.txt', 'w')
for i in range(0, 101): 
    var = (i * 2000)/100
    escreva = 'Temperature is: '+str(i)+'°C  converted is: '+str(var)+'\n'
    arquivo.write(escreva)
arquivo.close()

1


Just improving the answer already given, some tips.

You can use the with when defining the file Handler in a proper scope and so need not close it from the arquivo.close() in the end.

with open('escala.txt', 'w') as arquivo:
    for i in range(0, 101): 
        var = (i * 2000) / 100
        arquivo.write('Temperature is {}oC converted is {}\n'.format(i, var))

Another tip is to use the format() to mount his string as well as more intelligent than the str(), allows better control of the presentation (number of decimals, zero on the left etc).

Finally a mathematical hint, multiplying a number by 2000 and then dividing by 100 is the same thing as just multiplying by 20, one less operation at the end.

Browser other questions tagged

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