What Does Return True/False Actually Do? (Python) [Closed]

I've added in a sample code below just so you have a frame of reference for what my question actually is. I always see programs with if statements that return True or False, but what is actually happening here, why wouldn't you just want to put a print statement for false/true. I'm lost here.

def false(x,y):
    x > y
    return False

false(9,10)
1

Because most of the time you'll want to do something with the result other than print it. By using a return value, the function does one thing: do the calculation, and the caller can do whatever it wants with it: print it, write it to a database, use it as part of some larger calculation, whatever. The idea is called composability.

Also your example doesn't currently make much sense as it will always return False after evaluating x > y but doing nothing with the result. Perhaps you meant something like:

def is_greater(x, y):
    if x > y:
       return True
    else:
       return False

Then is_greater is something that can easily be used in whatever context you want. You could do:

x = is_greater(a, b)
write_to_super_secret_database(x)

(In real life you probably wouldn't use a function to do something so trivial, but hopefully the example makes sense.)

6

Functions which return True / False are used in further statements like IF:

Like this:

def is_bigger(x,y):
  return x > y

if is_bigger(10,9):
  do_something
elif:
  print "math don't work anymore"

you should take a look at variables and control structures:

2
Robert Thorne

Robert Thorne

Automotive & Future Transportation Editor

Robert Thorne covers electric vehicle innovations, autonomous driving systems, global mobility trends, and automotive engineering developments.

Share this article
Twitter Facebook Pinterest