Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

Python Python Basics Functions and Looping Returning Values

Trevor Funk
Trevor Funk
4,583 Points

Reviewing Functions Quiz question

The question says "there is a code smell in the code below:

first_number = 5 first-result = first_number * first_number print("The number {} squared is {}".format(first_number, first_result))

second_number = 8 second_result = second_number * second_number print("The number {} squared is {}".format(second_number, second_result))

It then asks "What could be done to fix the duplication of code?"

I understand that the answer is to create a function and have it accept a parameter of a number to square. However when I tried to actually code it in workspace to figure it out I wasn't sure how to do it. Could some one show me what the code would look like to actually fix this smelly code. Thanks

(P.s. Is there a way to show the question without having to type it out?) thanks

1 Answer

andren
andren
28,503 Points

There are a couple of different ways this could be coded, but here is the code I would have written:

def print_square(number):
    print("The number {} squared is {}".format(number, number * number))

print_square(5)
print_square(8)

That is one of the simplest solution I could think of, and it looks relatively clean.

Trevor Funk
Trevor Funk
4,583 Points

thanks that makes sense!