2014-09-29 61 views
1

下面是一个项目,我工作的一些代码:我需要修正哪些内容才能使此代码返回“True”?

# Make sure that the_flying_circus() returns True 
def the_flying_circus(): 

    if (3 < 4) and (-10 > -20):# Start coding here! 
     print "Hey now!"# Don't forget to indent 
     # the code inside this block! 
    elif (-4 != -4): 
     print "Egad!"# Keep going here. 
    else: 
     return True # You'll want to add the else statement, too! 

我不知道为什么,这不符合具有代码返回True的条件。有什么想法吗?

+4

由于表达式'(3 <4)和(-10> - 20)'总会是'真的'?或者我误解了你的问题? – 2014-09-29 21:08:38

+0

如果前面的if语句都不成立,'else'将会被执行。由于第一个条件是真的,否则不会执行。如果你总是想返回true,把它放在'else'分支之外。 – 2014-09-29 21:09:08

+0

尝试'print the_flying_circus()' – 2014-09-29 21:09:09

回答

0

这种情况总是TRUE

if (3 < 4) and (-10 > -20):# Start coding here! 
    print "Hey now!"# Don't forget to indent 
    # the code inside this block! 

所以脚本将始终打印:Hey now!。 没有机会,代码将在任何这些情况下结束。

elif (-4 != -4): 
    print "Egad!"# Keep going here. 
else: 
    return True # You'll want to add the else statement, too! 

这些条件是绝对没有必要的。只有你可以做的是改变第一个条件(例如使用一些变量,它将采取不同的值,因此条件将不会每次都是TRUE

2
(3 < 4) and (-10 > -20) 

好,3小于4.与-10-20更大。所以表达总是如此。你的函数不执行返回语句,因此返回None。你的函数可以重新写成这样:

def the_flying_circus(): 
    print "Hey now!" 
    return None 
+0

谢谢!我通过在if语句(当然是缩进)之后添加行return True来修复它并删除了print命令。基本上,我没有意识到我必须编写“返回True”部分......我假定Python知道我输入的内容是真实的。希望这是有道理的... – 2014-09-29 21:27:00

0
# Make sure that the_flying_circus() returns True def the_flying_circus(): 

    if (3 < 4) and (-10 > -20):# Start coding here! 
     print "Hey now!"# Don't forget to indent 
     # the code inside this block! 
    elif (-4 != -4): 
     print "Egad!"# Keep going here. 
    return True # You'll want to add the else statement, too! 

这将返回True。否则,你总是会得到“嘿,现在!”因为您的if条件始终为True

如果要在满足条件时返回True,则代码应该是

if (3 < 4) and (-10 > -20):# Start coding here! 
      print "Hey now!" 
      return True 
+0

谢谢!我注意到,返回True可以在打印命令之前出现。因此,根据自己的喜好,您可以在打印之前将其返回,反之亦然(不过,在这种情况下,不确定为什么这很重要)。 – 2014-09-29 21:24:16

+0

如果您在打印语句之前返回,则打印将不会执行。 – 2014-09-30 04:51:33

相关问题