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

Cory Ramirez
Cory Ramirez
4,257 Points

Converting arguments to integer, if allowed

Hello everyone,

I'm having a little issue with this challenge and am hoping someone could point me in the right direction if I'm thinking about this the right way.

I'm using modulus 2 to see if the result is an integer. If it is, I'm squaring it. However, I'm a little unsure though how to check if an argument is a string, and if it is, determining if its one that can or cannot be converted. How would I know exactly?

Thank you!

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

def squared(arg):
    try:
        if arg % 2 == int:
            return arg * arg
    except ValueError:
        print("This is not an integer!")
        else:
            return arg * len(arg)

2 Answers

Name:GoogleSearch orJonathan Sum
Name:GoogleSearch orJonathan Sum
5,039 Points

It looks like that most of treehouse student has already taken coding classes before. Unlike me, i am just a noob who haven't taken any of them before.

#I see you are using "arg % 2 == int" to test is the arg is a int or not. 
#However, when i am testing it in the python shell ,it gives me this:

>>>4%2==int
False
>>>5 ==int
False 
>>> int==int
True

#I guess that is because int is a class here. It is just like 5 is a value ,but int is a type. Althoug 5 is a int or integer ,value of 5 is not a type of int.

#I think you don't need to use if and else here. That try is very similar to if ,and that except is very similar to else. 

#This is how we using try and except

string="Hello"
    try: string = int(string)                #converting string into an int ,and it will fail.
        return string +1                        # since the try converting into int fails ,it won't run this line of code ,and it will go to the except block.              
    except ValueError:         
        print("if string can't not be convert into int, let's multiple the length of itself.")
        return  string * len( string)
Cory Ramirez
Cory Ramirez
4,257 Points

Thanks so much! solved my question. :)