Is_int


#1

https://www.codecademy.com/en/courses/python-intermediate-en-rCQKw/0/3?curriculum_id=4f89dab3d788890003000096
hi,
This passed the problem, but I'm almost certain I did something wrong
def is_int(asd):
////if asd%1==0:
////////return True
////else:
////////return False
can somebody explain what is wrong with this code?


#2

its correct , i tested it out
is_int(3)
True

is_int(3.0)
True

is_int(3.5)
False

its checking for a input HIGHER than 0 which outputs FALSE

Good Job ! :slight_smile:


#3

My code has the desired result but it is not passing:

numero = float(input("Write any number: "))
def is_int(x):
    to_string = str(x)
    a, b = to_string.split(".")
    a = int(a)
    b = int(b)
    if b == 0:
        return True
    else:
        return False

if is_int(numero) == True:
    print("The number %s is an integer" %(numero))
else:
    print("The number %s is NOT an integer" %(numero))

#4

I'm going to hazard a guess that when it is being tested a float isn't being passes to is_int(). Your script requires the input to be a float, an int wouldn't work.

Lets look at the output of the is_int() on it's own without the float numero user input:

>>> is_int(2)

Traceback (most recent call last):
  File "<pyshell#2>", line 1, in <module>
    is_int(2)
  File "<pyshell#1>", line 3, in is_int
    a, b = to_string.split(".")
ValueError: need more than 1 value to unpack

Why are we getting this error? Using the 2 from the example above.

>>> to_string = str(2)
>>> to_string.split(".")
['2']

As you can see, because there is no "." to split on you only get the one value returned, so there is no value to give to b, hence the ValueError.


#5

Thanks for your help jagking, yes I completely agree that if, in this particular code, you don't add a float to the is_int(float) you won't be able to unpack the value for b. However, the numero variable resolved this issue.

Looking at sumdude's code above I see it is much more efficient to use modulo (%) divided by one, to determine if there is a value in the decimal place. However, I still don't understand why my code, which works perfectly (albeit inefficient) does not pass.

Anyway, thanks jagking for all of your help. It doesn't really matter because my code wasn't too efficient anyway. Amazing to have such knowledgeable people willing to help us understand these concepts.


#6

Your code doesn't pass because the site doesn't run your code per se, it runs your is_int() function inputting what it wants to into it, i.e. non float values. So your numero variable isn't used. If that makes sense?

As a standalone script, it would work as you intended.


#8

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.