Home > Back-end >  is there a way to pass the output of a function as input to another function?
is there a way to pass the output of a function as input to another function?

Time:11-13

I am trying to create 2 functions. Function1: "choices", returns 2 strings "choice_a,choice_b", which I would like to use as input for Function2:"game"

how can I do this? what is wrong in this code? thanks

def general():
    choices()
    game(choices())

def choices():
    choice_a=input("A: rock, scissor or paper? \n")
    choice_b=input("B: rock, scissor or paper? \n")
    return choice_a,choice_b

CodePudding user response:

def general():
    return game(choices())

def choices():
    choice_a=input("A: rock, scissor or paper? \n")
    choice_b=input("B: rock, scissor or paper? \n")
    return choice_b , choice_b
def game():
    return choices();

general()

CodePudding user response:

If your function takes 2 arguments and the first function returns 2 variables (a tuple), you should use game(*choices()) (note the *) instead of game(choices())

CodePudding user response:

If you have multiple return values you can assign them to variables.

def general():
    a, b = choices()

Example output:

>>> print(a)
rock

>>> print(b)
scissors

And then you can use them as arguments:

def general():
    a, b = choices()
    game(a, b)

def choices():
    choice_a=input("A: rock, scissor or paper? \n")
    choice_b=input("B: rock, scissor or paper? \n")
    return choice_a, choice_b

def game(a, b):
    print(a, b)

CodePudding user response:

def general():
    choices() # you don't need this function call here
    game(choices())

def choices():
    choice_a=input("A: rock, scissor or paper? \n")
    choice_b=input("B: rock, scissor or paper? \n")
    return choice_a,choice_b  # return value is (choice_a, choice_b)

you get a tuple, (choice_a, choice_b) returned from the choices function.

I am assuming your game function takes two arguments, something like this:

def game(choice_a, choice_b):
    print(choice_a, choice_b)

The problem here is that you are passing one argument (choice_a, choice_b) which is a single tuple, but the game method is supposed to take two arguments.

You need to unpack the tuple if you want to use that, like below:

game(*choices()) 

because choices() will return (choice_a, choice_b), you can unpack it using the * operator.

Here is the complete code that you might find helpful:

def general():
    game(*choices())

def game(choice_a, choice_b):
    print(choice_a, choice_b)

def choices():
    choice_a=input("A: rock, scissor or paper? \n")
    choice_b=input("B: rock, scissor or paper? \n")
    return choice_a,choice_b

general()
  • Related