首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >Python :如何从从elif调用的函数中返回两个值?

Python :如何从从elif调用的函数中返回两个值?
EN

Stack Overflow用户
提问于 2021-01-08 06:39:43
回答 4查看 172关注 0票数 0

此处的elif someother_function():检查它是否为真,并且还需要打印返回的值。有人能帮我吗?

代码语言:javascript
运行
复制
def some_function():
     if correct:
         return True
     else:
         return False

def someother_function():
     if correct:
         return True,f
     else:
         return False,None


if some_function():
     print("something")
elif someother_function():
     print(f)
else:
     print("nothing")

在这里,如何将f从someother_function返回到它在elif调用的位置?

EN

回答 4

Stack Overflow用户

回答已采纳

发布于 2021-01-08 06:49:48

你可以试试:

代码语言:javascript
运行
复制
def some_function(correct):
   if correct:
       return False
   else:
       return False

def someother_function():
    if correct:
       return True, f
else:
    return False, None

if some_function():
    print("something")
elif [x := someother_function()] and x[0]:
    print(x[1])
else:
    print("nothing")
票数 1
EN

Stack Overflow用户

发布于 2021-01-08 07:06:04

如果需要,可以用函数编写类,并用输出设置类变量:

代码语言:javascript
运行
复制
import random

class foo:
    
    def __init__(self):
        self.f=None
        
    def some_function(self):
        correct= random.choice([True, False])
        if correct:
            return True
        else:
            return False

    def someother_function(self):
        self.f = "something 2"
        correct= random.choice([True, False])
        if correct:
            return True,
        else:
            return False,None

if __name__=="__main__":
    temp = foo()
    if temp.some_function():
         print("something")
    elif temp.someother_function():
         print(temp.f)
    else:
         print("nothing")
票数 0
EN

Stack Overflow用户

发布于 2021-01-08 07:42:27

我认为你需要指定一种事件。如果需要,请检查这段代码并尝试它:

代码语言:javascript
运行
复制
import random

event = random.choice([True, False])

def some_function(correct):
     if correct:
         return True
     else:
         return False

def someother_function(correct):
     if correct:
         return True, f
     else:
         return False, None


if event == True:
    some_function()
    print("something")
elif event == False:
    someother_function():
    print(f)
else:
    print("nothing")
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/65624470

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档