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) 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