首页 > 解决方案 > Python函数不返回任何内容

问题描述

我正在做我的任务,出现了一些问题,我想在我的函数中返回 true 或 false,但它最后什么也没显示。

import math
import decimal

#1
def pythagorean_pair():
    a = input("Type a number A(Must be an integer): ")
    if a.isdigit():
        a=int(a)
        b = input("Type a number B(Must be an integer): ")
        if b.isdigit():
            b = int(b)
            c = a**2 + b**2
            ans = c**(1/2)
            ans = ans - int(ans)
            if ans == 0:
                return (True)
                print ("True, they are pythagorean pair!")
            else:
                return (False)
                print ("False, they are not pythagorean pair!")
        else:
            print ("Please input an integer!!")
    else:
        print ("Please input an integer!!")
pythagorean_pair()

标签: pythonpython-3.x

解决方案


有一些回报,你必须得到print()它。

print(pythagorean_pair())

你似乎在问为什么函数除了打印什么都没有Ture/False。因为你在打印之前返回,所以函数在你返回时完成。所以print()不会执行。

改成:

if ans == 0:
    print ("True, they are pythagorean pair!")
    return (True)
else:       
    print ("False, they are not pythagorean pair!")
    return (False)

推荐阅读