0

What I need is for it to print "the sum of 1 and 2 is 3". I'm not sure how to add a and b because I either get an error or it says "the sum of a and b is sum".

def sumDescription (a,b):
    sum = a + b
    return "the sum of" + a " and" + b + "is" sum

3 Answers 3

3

You cannot concat ints to a string, use str.format and just pass in the parameters a,b and use a+b to get the sum:

def sumDescription (a,b): 
    return "the sum of {} and {} is {}".format(a,b, a+b)

sum is also a builtin function so best to avoid using it as a variable name.

If you were going to concatenate, you would need to cast to str:

def sumDescription (a,b):
   sm = a + b
   return "the sum of " + str(a) + " and " +  str(b) + " is " + str(sm)
Sign up to request clarification or add additional context in comments.

Comments

2

Use string interpolation, like this. Python will internally convert the numbers to strings.

def sumDescription(a,b):
    s = a + b
    d = "the sum of %s and %s is %s" % (a,b,s)

3 Comments

sumDescription(1.5, 4) -> the sum of 1 and 4 is 5
Touche. I guess it'll work to use the string notation because Python will automatically use str() to convert the int/float to a string
yep, using %f would give different output too, str.format just makes life simpler
1

You are trying to concatenate string and int.
You must turn that int to string before hand.

def sumDescription (a,b):
    sum = a + b
    return "the sum of " + str(a) + " and " + str(b) + " is " + str(sum)

Comments

Your Answer

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.