Python:函数定义在所需输出的中间不断返回'None'

Python:函数定义在所需输出的中间不断返回'None'

问题描述:

好吧,所以我正在为我们的女朋友制作我们的6周年代码。 我是一个完整的编程noob。我正在编写一些非常简单的代码,基本上是一个输入数字输入机器,以便用户(她)接收字符串输出。Python:函数定义在所需输出的中间不断返回'None'

我一直看到“无”,当我运行我的代码。为什么? 在这里。

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 " 
+0

我不知道为什么它的格式非常糟糕...... – davidawad 2013-03-17 03:02:33

+0

创建帖子时,可以选择突出显示代码块并单击“代码块”选项将其格式化为代码。 – Snukus 2013-03-17 03:04:30

+0

你可以做Snukus所说的,点击_code_按钮,或者你可以将所有代码缩进4个空格 - 这正是我编辑帖子时所做的。 – DaoWen 2013-03-17 03:05:31

你的函数具有None默认的返回值,所以当你print出来,将打印None

只需调用没有print语句的函数即可。

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

+0

Sheesh,谈论挑剔。 :P – Makoto 2013-03-17 03:08:48

love(0) # is all you need. 

你不需要调用print love(),因为你已经拥有内love打印报表。 你正在看到Nonelove正在做所有的工作,它没有返回任何东西。


另外,你需要为你只想要一个,出所有的打印操作的,在同一时间运行,以使用if-elif-else块的功能。

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 答案就这样!好极了 !

+0

好完美!谢谢。我的另一个问题是为什么总是打印else语句,即使对于前者。 n == 4是真的吗? – davidawad 2013-03-17 03:11:26

+0

您需要在第一个“elif”之后而不是if之后制作所有if语句。其他方面,你说的是:如果n不等于4,则打印else块中的内容。 – Snukus 2013-03-17 03:12:01

+0

ohhhhhhkay。我不知道它是这样工作的。谢谢! – davidawad 2013-03-17 04:22:21