I'm starting out in python and thought it'd be a good exercise to try to build a function that determines whether an input passed to it is an integer, and if so whether it's positive. At a later stage I plan to reference that function from within a mathematical function that only accepts positive integers.
Anyway, this is the function I built:
def is_ok(x): #checks if x is a positive integer
is_int = False
is_pos = False
if type(x) == int:
is_int = True # if it's an integer, continue to test if >0
if x > 0:
is_pos = True
else:
pass
else:
pass
return is_int, is_pos
as you can see, it gets one argument (the value to be tested) and returns a tuple of Trues and Falses.
Now, I don't know how to use the tuple outside the function... for instance, if I try to pass a number through the function and assign variable the values received, I get an error. I mean something like:
is_int, is_pos = is_ok(y)
y being some number, for example. this produces an error on run.
So basically what I'm trying to understand is how to do the following: function A accepts a value as its sole input ===> runs it through the is_ok(x) function ===> function A gets the tuple produced by is_ok() function and uses if/elifs to produce different results depending on the value of the tuple.
example for function A:
def get_value():
z = input("insert value" ")
is_ok(z)
if (is_int,is_pos) == (True, True):
print z**2
elif (is_int,is_pos) == (False, False):
print "Please enter an integer"
get_value()
elif (is_int, is_pos) == (True, False):
print "Please enter an positive integer"
get_value()
else:
print "something is wrong"
Help would be appreciated! Thanks!
====================== EDIT: late addition
when I run this on input 7 for example (any positive integer for that matter):
def is_ok(x): #checks if x is a positive integer
is_int = False
is_pos = False
if type(x) == int:
is_int = True # if it's an integer, continue to test if >0
if x > 0:
is_pos = True
else:
pass
else:
pass
return is_int, is_pos
#is_int, is_pos = is_ok(y)
#print is_ok(y)
#print is_int
#print is_pos
#is_ok(7)
def get_value():
z = input("insert value ")
is_int, is_pos = is_ok(z)
if (is_int,is_pos) == (True, True):
print z**2
elif (is_int,is_pos) == (False, False):
print "Please enter an integer"
get_value()
elif (is_int, is_pos) == (True, False):
print "Please enter an positive integer"
get_value()
else:
print "something is wrong"
get_value()
I get:
49 (True, False)
First Q: why False? Second Q: if false, why did it return what it should have for True, True Third Q: why did it print the tuple? No print statement
More help? :)