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

2024-05-16 01:42:45 发布

您现在位置:Python中文网/ 问答频道 /正文

好吧,我正在为我女朋友为我们6周年纪念做代码。 我对编程一窍不通。基本上是为了让用户输入一些简单的输入(m)指令。在

我运行代码时总是看到“无”。为什么? 好了。在

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 "

Tags: to代码用户youifthatdef编程
2条回答

您的函数有一个默认返回值None,因此当您print输出它时,它将打印None。在

只需调用不带print语句的函数。在

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

love(0) # is all you need.

您不需要调用print love(),因为在love中已经有print语句。 您看到的是None,因为love正在做所有的工作,并且它没有返回任何内容。在


另外,您需要在函数中使用if-elif-else块,因为您一次只想在所有打印操作中运行一个块。在

^{pr2}$

尽管,除了2,打印所有内容都不会有什么影响;)

我的100分回答!耶!

相关问题 更多 >