JamalCrawford..
JamalCrawford..

Reputation: 187

concatenation of strings and variables

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

Upvotes: 0

Views: 115

Answers (3)

wpercy
wpercy

Reputation: 10090

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)

Upvotes: 2

Padraic Cunningham
Padraic Cunningham

Reputation: 180401

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)

Upvotes: 3

taesu
taesu

Reputation: 4580

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)

Upvotes: 1

Related Questions