首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Python:函数返回none

Python:函数返回none
EN

Stack Overflow用户
提问于 2021-02-15 16:34:58
回答 2查看 71关注 0票数 0
代码语言:javascript
复制
def divide(x,y):
    if x <0 or y <= 0:
        return 0,0 
    quotient = 0
    while x >= y:
        x -= y
        quotient += 1
    return quotient,x #remainder is in x

def main():
    x,y = input("Enter digits separated by comma: ").split(",")
    x,y = int(x),int(y)
    divide(x,y)
    
main()

2个数x除以y,从x中减去y,直到y小于x。例如,x= 11,y= 4。商是2(减去两次),余数是3 (11-4-4=3)。

我期望返回tupple of (2,3),但它一直没有返回给我。我想知道我在哪里犯了错,以及我如何改进。提前谢谢你!!

EN

回答 2

Stack Overflow用户

发布于 2021-02-15 16:38:19

您的函数将返回一个元组。您没有使用它。

变化

代码语言:javascript
复制
divide(x, y)

代码语言:javascript
复制
res = divide(x, y)
print(res)

如果你想在main之外使用结果,你可以返回它,它看起来像这样,

代码语言:javascript
复制
def divide(x,y):
    if x <0 or y <= 0:
        return 0,0
    quotient = 0
    while x >= y:
        x -= y
        quotient += 1
    return quotient,x #remainder is in x

def main():
    x,y = input("Enter digits separated by comma: ").split(",")
    x,y = int(x),int(y)
    return divide(x,y)

res = main() # catch the value returned
print(res) # use the returned value
票数 0
EN

Stack Overflow用户

发布于 2021-02-15 16:38:26

您的main方法不返回任何内容。

除此之外,您的应用程序可以做您想要的事情:

代码语言:javascript
复制
def divide(x,y):
    if x <0 or y <= 0:
        return 0,0
    quotient = 0
    while x >= y:
        x -= y
        quotient += 1
    return quotient,x #remainder is in x

def main():
    x,y = input("Enter digits separated by comma: ").split(",")
    x,y = int(x),int(y)
    return divide(x,y) # return the result of ``divide``.

print(main()) # do something with the result of ``main``, e.g. print it

输出:

代码语言:javascript
复制
 (2, 3)

Side node: Python中的每个方法都会返回一些东西。如果您没有显式地设置它,结果将被隐式设置为None

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/66204838

复制
相关文章

相似问题

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