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 "
答
你的函数具有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
打印报表。 你正在看到None
为love
正在做所有的工作,它没有返回任何东西。
另外,你需要为你只想要一个,出所有的打印操作的,在同一时间运行,以使用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 日答案就这样!好极了 !
我不知道为什么它的格式非常糟糕...... – davidawad 2013-03-17 03:02:33
创建帖子时,可以选择突出显示代码块并单击“代码块”选项将其格式化为代码。 – Snukus 2013-03-17 03:04:30
你可以做Snukus所说的,点击_code_按钮,或者你可以将所有代码缩进4个空格 - 这正是我编辑帖子时所做的。 – DaoWen 2013-03-17 03:05:31