How to write in a file the number typed by the user and the value given by the program?

Asked

Viewed 30 times

1

How can I write only the value typed by the user (the value of n typed by it) and the result given by the program (reply) into a single file?

def fibonacci(n):
  
    r = [-1]*(n + 1)
    return fibonacci_2(n, r)
 
 
def fibonacci_2(n, r):
    
    if r[n] >= 0:
        return r[n]
 
    if (n == 0 or n == 1):
        q = n
    else:
        q = fibonacci_2(n - 1, r) + fibonacci_2(n - 2, r)
    r[n] = q
 
    return q
 
 
n = int(input('Digite um valor para n: '))
 
resposta = fibonacci(n)
print('O', n, 'termo da sequência de Fibonacci é:', resposta)

1 answer

3

To perform read and write operations on an archive you must do the following:

    arquivo= open( “nome_do_arquivo.txt”,”w” ) 
     
    arquivo.write( “valor providenciado pelo usuario: ” + str(n) ) 
    arquivo.write( “termo da sequência de Fibonacci é: ” + str(resposta) 
    
     
    arquivo.close()

follows the python documentation reference.

  • It’s nice to put a " n" there to change lines inside the file.

Browser other questions tagged

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