为什么这个程序总是返回“无”?

时间:2013-10-17 00:45:38

标签: python if-statement

def ticketdo(tickethave):
    phrase = "Your total is $"
    if tickethave == "n":
        print phrase + "22"
    elif tickethave != "n":
        tickethour = input("How long has your car been parked?")
        if tickethour <=1:
            print phrase + "2"
        elif tickethour <=2:
            print phrase + "4"
        elif tickethour <=3:
            print phrase + "6"
        elif tickethour <=4:
            print phrase + "8"
        elif tickethour <=5:
            print phrase + "10"
        elif tickethour <=6:
            print phrase + "12"
        elif tickethour <=7:
            print phrase + "14"
        elif tickethour <=8:
            print phrase + "16"
        elif tickethour > 8:
            print phrase + "20"

def main():
    tickethave = raw_input("Do you have your ticket? (y/n): ")  

    print ticketdo(tickethave)

main()

3 个答案:

答案 0 :(得分:3)

这是因为ticketdo没有返回任何内容。默认情况下,不返回任何内容的函数返回None。这是因为,在Python中,所有函数都必须返回某些东西

此外,通过:

print ticketdo(tickethave)

你告诉Python打印ticketdo的返回值。

因此,要解决此问题,请将print放在该行上或让ticketdo返回一些内容然后打印出来(根据您的代码结构判断,您可能需要第一个解决方案)。< / p>

答案 1 :(得分:0)

您正在打印ticketdo功能的返回值。由于您没有明确指定该函数的返回值,因此它将自动返回默认值None,这正是您要打印到stdout的内容。

如果你想简单地调用函数而不打印它的返回值,只需执行:

ticketdo(tickethave)

调用函数时,不需要对函数的返回值执行任何操作。使用返回值完全是可选的。

答案 2 :(得分:-1)

我只是在ticketdo(tickethave)之前删除了打印:

#!/usr/bin/env python

def ticketdo(tickethave):
    phrase = "Your total is $"
    if tickethave == "n":
        print phrase + "22"
    elif tickethave != "n":
        tickethour = input("How long has your car been parked?")
        if tickethour <=1:
            print phrase + "2"
        elif tickethour <=2:
            print phrase + "4"
        elif tickethour <=3:
            print phrase + "6"
        elif tickethour <=4:
            print phrase + "8"
        elif tickethour <=5:
            print phrase + "10"
        elif tickethour <=6:
            print phrase + "12"
        elif tickethour <=7:
            print phrase + "14"
        elif tickethour <=8:
            print phrase + "16"
        elif tickethour > 8:
            print phrase + "20"

def main():
    tickethave = raw_input("Do you have your ticket? (y/n): ")  

    ticketdo(tickethave)

if __name__ == "__main__":

    main()