-2

So i'm creating a little experimental python program and I'm using a little tidbit of code (shown below) to determine if a number is whole or has decimal places.

def isWhole(x):
if(x%1 == 0):
    return "1"
else:
    return "2"

My problem is that no matter where I go I can't find a way to just take the returned value and assign it to a variable...

Sorry if I seem like an absolute spurglord noob for asking this question but I never even knew that functions could "return" until about 2 days ago, so yeah...

Ben Lonc
  • 11
  • 2
  • http://stackoverflow.com/questions/3501382/checking-whether-a-variable-is-an-integer-or-not You should return true or False instead of 1 or 2 :) – fdglefevre Mar 29 '15 at 22:42
  • After you figure out what value to use for `%` (hint: x % 1 is ALWAYS 0), you can use `(1,2)[x % 2]` for example to return 1 or 2 based on even / odd – the wolf Mar 29 '15 at 22:56
  • @Florian: In this case you could do that with `return x%1 == 0` (which would always return `True`, for the previously stated reason). – martineau Mar 29 '15 at 23:26

4 Answers4

2

like this:

def isWhole(x):
    if(x%1 == 0):
        return "1"
    else:
        return "2"

my_var = isWhole(4)
Jaakko
  • 584
  • 6
  • 13
1

The return value will always be 1.

def isWhole(x):
    if x % 1 == 0:
        return "1"
    else:
        return "2"

if __name__ == "__main__":
    k = isWhole(4)
    print(k)
demo.b
  • 3,299
  • 2
  • 29
  • 29
1

Answering your question, how to assign a variable, just assign it to the output of the function as below:

var = isWhole(4) #Put any number in instead of 4

As long as you have a return in your function, you can assign a variable to the output:

>>> def foo():
...    return "bar"
...
>>> var = foo()
>>> var
"bar"
>>>

However if you do not have a return, then it returns None, so beware :)

>>> def bar():
...    print "foo"
...
>>> var = bar()
foo
>>> var
None
>>>
A.J. Uppal
  • 19,117
  • 6
  • 45
  • 76
1

As others have explained, you can just assign the result of calling the function to a variable name to save the value. Perhaps equally important though, is the fact that the code shown in your function will always return "1" since the value of x%1 is always going to be 0 regardless of the value of x (assuming its value is non-zero and a type with a modulo operator).

I would suggest that tou instead implement your function to return a True or False value and do it like the following:

def is_whole(x):
    return float(x).is_integer()

(See the is_integer documentation for more information.)

You can assign the result of calling this function to a variable as shown below:

result1 = is_whole(21./7.)  # assign function return value to a variable
result2 = is_whole(22./7.)  # assign function return value to another variable

print(result1)  # --> True
print(result2)  # --> False
martineau
  • 119,623
  • 25
  • 170
  • 301