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,550 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,550 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