【问题标题】:Python: How do I assign 2 values I return from a function with 1 input as values outside the function?Python:如何将我从具有 1 个输入的函数返回的 2 个值分配为函数外部的值?
【发布时间】:2014-03-25 09:16:03
【问题描述】:

我从 python 开始,并认为尝试构建一个函数来确定传递给它的输入是否为整数,如果是,则它是否为正数是一个很好的练习。在稍后阶段,我计划从只接受正整数的数学函数中引用该函数。

不管怎样,这是我构建的函数:

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

如您所见,它获取一个参数(要测试的值)并返回一个 True 和 False 元组。

现在,我不知道如何在函数外部使用元组...例如,如果我尝试通过函数传递一个数字并将接收到的值分配给变量,我会收到错误消息。我的意思是:

is_int, is_pos = is_ok(y)

y 是一些数字,例如。这会在运行时产生错误。

所以基本上我想了解的是如何执行以下操作: 函数 A 接受一个值作为其唯一输入 ===> 通过 is_ok(x) 函数运行它 ===> 函数 A 获取 is_ok() 函数生成的元组并使用 if/elifs 根据值生成不同的结果元组。

函数 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"

我们将不胜感激! 谢谢!

======================= 编辑:后期添加

例如,当我在输入 7 上运行它时(任何正整数):

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()

我明白了:

49 (对,错)

第一问:为什么是假的? 第二个问题:如果为假,为什么它返回它应该有的东西为真,真 第三问:为什么要打印元组?没有打印语句

更多帮助? :)

【问题讨论】:

  • 你得到什么错误?您显示的示例调用是正确的。但是,在get_value() 中,您未能将is_ok() 的返回值分配给is_intis_pos
  • 感谢您发现这一点。基本上,当我传递一个正整数时,我得到的元组是(True,False),对于初学者。顺便说一句,现在我还发现了用户尝试传递字符串时会遇到的问题
  • 也请注意我的编辑。谢谢!

标签: python function scope return tuples


【解决方案1】:

正如 chepner 在 cmets 中提到的那样,你在正确的轨道上,但你正在放弃你的结果!

就我个人而言,我不会做你正在做的事情,我会为每一件事单独检查它(而不是使用一个函数来检查关于一个变量的两个事实并返回每个事实)。但是,如果您想按照自己的方式进行操作,则需要执行以下操作:

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"

如果我是你,我会写这样的:

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.

我们在 Python2 中不使用 input 的原因是它会执行你写出的任何 Python 代码。如果我输入import os; for file in os.listdir("C:/windows/system32"): os.remove(file),它将删除C:\Windows\System32 中的所有文件。我想我不必告诉你为什么这很糟糕! :)

【讨论】:

  • 好东西@adsmith,好东西。另外,我认为了解输入的陷阱很重要:D 非常感谢!
  • 你介意看看我对原始帖子(底部)所做的编辑,看看你是否能理解我为什么得到这些输出?再次感谢:)
  • @Optimesh 我逐行复制了您的代码行,但我没有得到与您相同的输出。我认为您需要再次查看本地代码:)
  • 奇怪!无论如何谢谢:)(是的,现在看起来好多了。令人难以置信!)
【解决方案2】:

如果要返回两个值,可以将它们作为列表返回,如下所示: return [value1, value2]

如果您的目标是验证输入以确保它是一个正整数,我会这样做:

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"

【讨论】:

    猜你喜欢
    • 2022-01-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-02-10
    • 1970-01-01
    相关资源
    最近更新 更多