打印包含if语句的函数,Python

时间:2018-01-24 12:03:35

标签: python-2.7 function if-statement printf

我试图在Visual Studio上用Python打印我的函数,它有很多" if"其中的陈述:

def correction(Diff):
    if 1 <= Diff <20 : 
        print "correction 1" # is correction necessary?
    elif 20 <= Diff < 49:
        print "correction 2" # Slight turn to right
    elif 50 <= Diff < 74:
        print "correction 3" # turn to right
    elif 75 <= Diff < 100:
        print "correction 4" # 'sharp' turn to right
    elif 100 <= Diff:
        print "correction 9" # STOP
    elif -20 <= Diff < 0:
        print "correction 5" # is correction necessary?
    elif -50 <= Diff < -20:
        print "correction 6" # Slight turn to left
    elif -75 <= Diff < -50:
        print "correction 7" # turn to left
    elif -100 < Diff < -75:
        print "correction 8" # 'sharp' turn to left
    elif Diff9 <= -100:
        print "correction 9" # STOP
    else:
        print "carry on"
return correction

print (correction)

在函数之前完全定义了Diff。但是,当我运行代码时,我会显示此消息代替print:

function correction at 0x073EECB0

我希望该函数能够运行并打印正确的语句。希望转移此代码以用于视频,因此任何可以最大限度地降低处理能力的建议和帮助都会很棒。

1 个答案:

答案 0 :(得分:1)

您的函数确实会返回对自身的引用。 为了简单地运行函数correction,只需像这样调用它

def correction(Diff):
    # code here

correction(PARAMETER)

PARAMETER是您选择的值。该函数本身包含打印语句,因此您无需在该函数之外担心它。

打印correction将&#34;打印&#34;该函数,导致其在内存中的地址被显示。

这就是它的工作方式

def correction(Diff):
    if 1 <= Diff <20 : 
        print "correction 1" # is correction necessary?
    elif 20 <= Diff < 49:
        print "correction 2" # Slight turn to right
    elif 50 <= Diff < 74:
        print "correction 3" # turn to right
    elif 75 <= Diff < 100:
        print "correction 4" # 'sharp' turn to right
    elif 100 <= Diff:
        print "correction 9" # STOP
    elif -20 <= Diff < 0:
        print "correction 5" # is correction necessary?
    elif -50 <= Diff < -20:
        print "correction 6" # Slight turn to left
    elif -75 <= Diff < -50:
        print "correction 7" # turn to left
    elif -100 < Diff < -75:
        print "correction 8" # 'sharp' turn to left
    elif Diff9 <= -100:
        print "correction 9" # STOP
    else:
        print "carry on"

correction(Diff) # Pass any integer or integer variable here

删除了返回对函数本身的引用的return语句,并将print语句更改为correction()的简单调用。