Python:函数定义在所需输出的中间保持返回“None”

时间:2013-03-17 03:02:01

标签: python

好的,所以我为我的女朋友为我们的6周年纪念做代码。 我是编程的完整菜鸟。我正在编写一些非常简单的代码,基本上是数字输入的输入输出机器,以便用户(她)接收字符串输出。

当我运行我的代码时,我一直看到“无”。为什么? 开始。

def love(n):
  if n < 0 : 
    print "Why would it be negative?!" 
  if n == 0 : 
      print "well that is just hurtful" 
  if n == 1 :
    print "I REALLY love you" 
  if n == 2 : 
    print "You make me smile at least once, each and every day"
  if n == 3 : 
    print"you wouldn't believe how annoying it was to get this program to run properly! but it was worth it"
  if n == 4 : 
      print "let's " + "shoot a little higher than that"
  else:
    print "I honestly can't see myself without you anymore" 


print love(0) 

print "Wanna try again? :D "

2 个答案:

答案 0 :(得分:7)

love(0) # is all you need.

您不需要致电print love(),因为您已经在love内打印了对帐单。 您看到None love正在完成所有工作,并且没有返回任何内容。


此外,您需要在功能中使用if-elif-else块,因为您希望一次只运行所有打印操作中的 one

if n < 0 : 
    print "Why would it be negative?!" 
elif n == 0 : 
      print "well that is just hurtful" 
elif n == 1 :
    print "I REALLY love you" 
elif n == 2 : 
    print "You make me smile at least once, each and every day"
elif n == 3 : 
    print"you wouldn't believe how annoying it was to get this program to run properly! but it was worth it"
elif n == 4 : 
      print "let's " + "shoot a little higher than that"
else:
    print "I honestly can't see myself without you anymore" 

虽然超出2,打印一切都不会受到伤害;)

我的100 th 回答SO!耶!

答案 1 :(得分:1)

您的函数的默认返回值为None,因此当您print它时,它将打印None

只需在没有print声明的情况下调用该函数。

或者,您可以使用print替换函数中的所有return语句,并将其转换为if-elif-else块,因为它们都是互斥操作。然后,打印love(0)实际上会打印出返回值。