Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Python Python Basics (2015) Logic in Python Fully Functional

Donald Tam
Donald Tam
1,570 Points

using {}.format in function for (a+b) handling

I am try to write something as below:


def average(a,b):
return [({}+{}).format(a,b)]
avg = average(3,4)
print (avg)

it told me:

return [({}+{}).format(a,b)]
TypeError: unsupported operand type(s) for +: 'dict' and 'd ict'


Please anyone can to me what wrong I am doing?

I want to try:

use .format in + or *, it that it would be not ok?? is that .format only can be use between "XXX" ????

I also want to try:


print("Love " * {}).format( count) seem also fail.


Pls advise and much appreciate

2 Answers

Hi Donald,

The curly braces are placeholders that are used inside the string to insert the values held by variables, or direct numbers. So, something like:

"{} times {} equals {}".format(a, b, a*b)

Depending on the values of a & b, you'd get the output "3 times 4 equals 12".

For your first code block, there's nothing to create an average yet but we could do something like:

def average(a,b):
  ave = (a + b) / 2
  return "The average of {} and {} is {}".format(a, b, ave)
avg = average(3,4)
print (avg)

Here, the value held by a goes in the first {}, b goes in the second {} and the last {} is filled with the value of ave.

And you second code block could look like:

print("Love  * {}").format( count) 

For that, I just moved the closing inverted comma so that the {} was inside the string.

I hope that helps.

Steve.

Donald Tam
Donald Tam
1,570 Points

Thx for help. it mean that .format(XXX) only can be use inside string.

Noted and thats