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 (2015) Number Game App Squared

Ali Dahud
Ali Dahud
3,459 Points

Could you break down this code for me? Step by step

Could you please?

squared.py
# EXAMPLES
# squared(5) would return 25
# squared("2") would return 4
# squared("tim") would return "timtimtim"

def squared(item):
    try:
        return int((item) ** 2)
    except:
        length = len(item)
        return item*length

2 Answers

Elgene Ee
Elgene Ee
3,554 Points

Oh I see Ali, It is okay to get frustrated sometimes, but just make sure you practice... So we want integers to get squared, there are 2 ways to square them

  1. (item * item)
  2. (item ** 2) the int function is to ensure that the output is integer( let's say we type squared(4.3), the outcome will be 4 with the help of int function)

Now things get a bit tricky, is to multiply strings, but how... We need the len function to get number of words we have...(let's say 'hello' has 5 chars) --> return item * len(item) This function multiply the strings with the number of chars it has.

Hope that helps

Elgene Ee
Elgene Ee
3,554 Points

Hi Ali, As you multiply a string(let's say "hi") with any integer(let's say 2), it will turn out to be --> ("hihi") Good job that at least you understand in try block! Keep it up

def squared(item):
    try:
            return int(item) ** 2
    except:
            return item * len(item)
Ali Dahud
Ali Dahud
3,459 Points

Actually I don’t understand anything from it. :( I just copied someone else’s code