How do I use the same argument/parameter in two different functions?

Asked

Viewed 324 times

1

Example:

 def seno1(x = int(input("Entre com x: ")),n=int(input("Entre com n: "))):
 def cos1(x,n):

How do I take advantage of the user input value of x and n in this function as well?

Thank you

2 answers

4

Don’t try to do everything in a single row - simply assign variables to your parameters typed with input:

def seno1(x, n):
   ...
def cos1(x,n):
   ...

# e mais abaixo no seu código ponha o trecho:
x = int(input("Entre com x: "))
n = int(input("Entre com n: "))

print(seno1(x, n))
print(cos1(x, n))

That way you’ll be in fact using its functions as functions and not only to reorganize the code, but still not reusable (because the way you did, those input would only be executed once, even if Voce called the function sen1 several times)- and if you put input and calls inside a while or another function, you can have a complete program that rewrites the calculations with various values.

1

I think it’s best to follow @jsbueno’s suggestion (this is an add-on).

By leveraging your code, you can use global variables (not indicated):

def seno1(x = int(input("Entre com x: ")),n=int(input("Entre com n: "))):
    global xg # cria variável global para x
    global ng
    xg = x # copia x para a variável
    ng = n

To use them, however, you would have to call the function seno1():

seno1() # chama função
print('variavel global x: ' + str(xg)) // mostra valor de x, fora de seno1()
print('variavel global n: ' + str(ng))

A third option is to put user input into another function:

def inputUsuario():
    x = int(input("Entre com x:"))
    n = int(input("Entre com n:"))
    return(x, n)

And then use it in a modified version of password1():

def seno1(x, y): # versão modificada de seno1(), só imprime variáveis
    print('x: ' + str(x) + ', y: ' + str(y))

# utilizando as duas funções

minhaVar = inputUsuario()
seno1(minhaVar[0], minhaVar[1])

Upshot:

inserir a descrição da imagem aqui

Browser other questions tagged

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