简体   繁体   中英

What do I need to fix to make this code return “True”?

Here's some code for a project I am working on:

# 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!

I am not sure why this doesn't satisfy the condition of having the code return True . Any thoughts?

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

Well, 3 is less than 4. And -10 is greater than -20 . So that expression is always true. Your function does not execute a return statement and so returns None . Your function could be re-written like this:

def the_flying_circus():
    print "Hey now!"
    return None
# 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!

This returns True . Otherwise, you're always going to get "Hey now!" because your if condition is always True .

If you want to return True when the condition is met, then the code should be

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

This condition is always TRUE :

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

So the script will always print: Hey now! . There is no chance, the code will ends in any of these conditions.

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

These conditions are absolutely unnecessary. Only thing you can do is change the first condition (eg use some variable, which will take different values so the condition won't be TRUE every time)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM