Part_Time_Nerd
Part_Time_Nerd

Reputation: 1014

What's wrong with my python function?

I am trying to design a recursive function that accepts two arguments from a user and puts them into parameters x and y. The function should return the value of x times y. My code is failing to execute correctly because of how I am trying to pass the x and y variable in the return statement but I cannot figure out what I am doing wrong.

def main():

    #get the user to input a two integers and defines them as x and y
    x = int(input("Please enter a positive integer: "))
    y = int(input("Please enter a second positive integer: "))

    #make sure the integer selection falls within the parameters
    if (y == 0):
        return 0
    return x+(x,y-1)

#call the main function
main()

My traceback says:

return x+(x,y-1) TypeError: unsupported operand type(s) for +: 'int' and 'tuple'

Upvotes: 0

Views: 150

Answers (2)

Yoav Glazner
Yoav Glazner

Reputation: 8066

def main():

    #get the user to input a two integers and defines them as x and y
    x = int(input("Please enter a positive integer: "))
    y = int(input("Please enter a second positive integer: "))

    print( mul(x, y) )

def mul(x, y):
    if y==0: return 0
    return x + mul(x, y-1)

Upvotes: 1

caffreyd
caffreyd

Reputation: 1203

`You might try something along these lines:

def main():

    #get the user to input a two integers and defines them as x and y
    x = int(input("Please enter a positive integer: "))
    y = int(input("Please enter a second positive integer: "))

    print recursive_mult(x, y)

def recursive_mult(x, y):
    if y == 0:
        return 0
    return x + recursive_mult(x, y - 1)

The error you're seeing is caused by trying to add an int value x to the tuple of (x, y - 1), where instead you probably want to be making a recursive call to some function with these values and add the result to x.

Upvotes: 1

Related Questions