Py学习  »  Python

python函数不返回任何内容

J.Xu • 7 年前 • 2055 次点击  

我正在做我的作业,结果出现了一些问题,我想在我的函数中返回“真”或“假”,但最后什么也没有显示。

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()
Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/39197
文章 [ 3 ]  |  最新文章 7 年前
kcorlidy
Reply   •   1 楼
kcorlidy    8 年前

有东西回来了,你必须 print() 它。

print(pythagorean_pair())

你好像在问 为什么函数只打印 Ture/False 。因为您在打印前返回,所以返回时功能完成。所以 打印() 不会执行。

更改为:

if ans == 0:
    print ("True, they are pythagorean pair!")
    return (True)
else:       
    print ("False, they are not pythagorean pair!")
    return (False)
Daniel Mojahedi
Reply   •   2 楼
Daniel Mojahedi    8 年前

除非您使用函数的输出来输入示例中未显示的代码

例如.,

boolean_value = pythagorean_pair() 

没有规定您必须有一个RETURN语句。换句话说,只需让函数打印字符串,就可以完成了。

def check_answer(boolean_answer):
    print("The answer is", boolean_answer)

check_answer(answer)
Chends
Reply   •   3 楼
Chends    8 年前

我测试了你的功能,正如其他人所说,如果你想打印一些东西,一定要在返回之前打印出来。因为什么 返回 Do只是返回输出并退出函数调用(我的意思是:下面什么都没有 返回 将运行)。您可以执行如下操作来测试代码:

def test(a):
    if a:
        return True
    return False

a = None
if test(a):
    print("True, input is not null")
else:
    print("False, input is null!")

返回:

False, input is null!