0

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'

asked Apr 30, 2017 at 6:41
3
  • What are you hoping to compute with x + (x, y - 1) ? Commented Apr 30, 2017 at 6:50
  • @donkopotamus I updated my question but the answer is, "The function should return the value of x times y." Commented Apr 30, 2017 at 6:54
  • 1
    Why not just return x*y ...? As the error says, you can't add an integer, x, to a tuple, (x,y-1). Commented Apr 30, 2017 at 6:56

2 Answers 2

1

`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.

answered Apr 30, 2017 at 6:59
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks caffreyd I had something almost identical to yours and @Yoav Glazner answer but I was getting an error due to how I had the print statement. I corrected your print statement with appropriate brackets and accepted your answer.
1
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)
answered Apr 30, 2017 at 6:59

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.