Python: How do I assign 2 values I return from a f

2019-09-01 16:54发布

问题:

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? :)

回答1:

As chepner mentioned in the comments, you're on the right track but you're throwing away your results!

Personally, I wouldn't do what you're doing, I would check it separately for each thing (as opposed to using one function to check two facts about a variable and return each fact). But if you WANT to do it your way, here's what you'd need to do:

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

def get_value():
    z = input("insert value: ")
    is_int, is_pos = is_ok(z)
    if (is_int,is_pos) == (True, True): # could also do `if all(is_int,is_pos):`
        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"

If I were you, I'd write something like:

def get_value():
    while True:
        z = input("Insert value: ") # DON'T DO THIS, INPUT() IS BADDDDD IN PYTHON2
        # instead do:
        ## try: z = int(raw_input("Insert value: "))
        ## except ValueError:
        ##     print("Please provide an integer")
        ##     continue
        # this also FORCES z to be an integer, so isinstance(z,int) is ALWAYS TRUE
        is_int = isinstance(z,int)
        is_pos = is_int and z>0 # this will keep you from throwing an exception if
                                # you can't compare z>0 because z isn't int
        if is_int and is_pos:
            print z**2
        elif is_int:
            print "Please provide an integer"
            continue
        else:
            print "Integer must be positive"
            continue
        # nothing can ever get to that last else block you had.

The reason we don't use input in Python2 is that it executes whatever you write out as Python code. If I entered import os; for file in os.listdir("C:/windows/system32"): os.remove(file) it would delete every file in C:\Windows\System32. I don't think I have to tell you why that's bad! :)



回答2:

If you want to return two values, you can return them as a list like this: return [value1, value2]

If your goal is to validate input to make sure it's a positive integer, this is how I'd do it:

def get_value():
    while True:
        try:
            z = int(raw_input("insert value: "))
            if z > 0:
                return z
            else:
                print "Please enter a positive integer"
        except ValueError:
            print "Please enter an integer"