The ABCs of Python: “raise,” “return,” “while” and knowing when to quit

Here are three more Python keywords. I know they look like a bit of a hodgepodge. Perhaps I should have discussed raise when I discussed the other exception handling words and while when covering for and in.  But, at least this way I get to keep some semblance of alphabetical order. What’s more, as I wrote this, I realized there’s a common theme for all these keywords: that is, they help our code know when to quit.

raise

Among Python keywords, raise is used to “raise” a virtual penalty flag for the user, telling them that there’s a problem.  You may remember our power_up_index function from before. We’re going to put it back into action, except we’ll engage the keyword raise.

def power_up_index(array, n):    

    '''
    Find Nth power of the element with index N.
    '''

    if len(array) < (n +1):
        raise IndexError
    else:
        return array[n]**n
   
print(power_up_index ([20, 12, 99, 15, 78], 3))
'''
n is the number 3 in this case. So, you pick the third
number, which is 15 in this case, and multiply that 
number by itself three times.
'''

print(power_up_index([1, 2, 3, 4], 2)) #you multiply the second number, which is 3 
                                       #since Python counts from 0, 
                                       #by itself two times so you get 9

print(power_up_index([1, 2], 3))
'''
you get an error message -- specifically an IndexError -- 
because the computer cannot locate the third number in 
this array (which only has two numbers,
as you can see).
'''

This code will produce something like this:

3375
9
raise IndexError
IndexError

return

When first learning to code in Python, there were few words more puzzling  to me than return.   I kept wanting to use print statements in lieu of return because I could see some results from print statements whereas not much seemed to be happening when I used return.  I didn’t quite grok its critical function. The depth of ignorance must seem bonkers to any seasoned coder.

So, when do you use return and what does it do? Here’s a metaphor. There’s a busy person who never goes to the post office or a public mail box to post a letter. Instead, she sticks her outgoing mail in her private mailbox when she is leaving to go to work in the morning. The postal worker picks up her outgoing mail and then posts it for her.

In a sense, this is how return works.  It only lives inside a function, as the woman lives in her house. It is used to exit the function and provide some sort of value. So, imagine the woman going to her mailbox and posting a letter with a single value on it. Maybe the value is a number or a string or a Boolean, but it’s something useful.  That message gets sent somewhere else (maybe to another function) where it becomes essential input. Failing to put the return in the function is sort of writing a letter and then forgetting to put it in the box. Nobody gets it.

It’s also sort of like posting a blank sheet of paper. That is, when you forget to add a return statement, the function will not know what to do and so just spit out the word None.

Of course, a simpler metaphor is that return hits the Enter key in your code. You’re not going to input much without hitting that key.

Anyway, here’s a quick example of how it works, an example inspired by the one in Programiz:

def send_letter():
    x = "letter"
    return x

print(send_letter())


def send_nothing():
    x = "letter"

print(send_nothing())

If we run this code, we’ll see that the first print statement produces the word “letter”. The second one, however, will produce “None”. That’s because we forgot to “post the letter” — that is, forgot to add the return statement in that function.

I should note that there are cases of functions that don’t require a return, such as the on-the-fly functions produced with lambda.  And there is also code that only needs to do something (such as print a statement) without returning anything. But let’s keep things simple for now. Just remember that if you write a function without a return, then the function doesn’t produce a value (except for None) even if the rest of the code in your function is perfect.

while

We won’t dwell too much on the supremely powerful while keyword because I wrote a whole post on it before. Just remember that while is used to create loops and that those loops will continue to run until the condition (or conditions) for them no longer applies (or until the loop runs smack into a break statement).  If you write a while statement incorrectly (which is not so hard to do), your code will get stuck in an infinite loop that will ultimately crash your program (if that happens, use Control-C). Here’s a simple program that uses while.

numbers = list()
counter = 0
while (counter <= 20):
    numbers.append(counter)
    counter = counter+2
print(numbers)

You should end up with a list like this: [0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20]

Note that this program hinges on the line counter = counter+2. That line increases the value of counter until it is equal to or more than 20, thereby letting the code know when to stop  And knowing when to stop is one of the great secrets in life

For more information on Python keywords, I recommend Zetcode

Why Not Take a Walk on the “While” Side?

On how to use “while” loops in Python

I like the language of the “while” loop because it verges on real-life, commonsense English.  After all, we run these kind of loops all the time in our daily lives.  For example, while my neighbor’s tree is producing lychee nuts and I’m allowed to pick them, I’m damn well going to pick some.  Once it stops producing good fruit (or once my neighbors tell me to take a hike), I’ll cease picking them.

“While loops” work the same way in Python. While a condition is True (or False), the code will do something. After that, it’ll stop.

Take the following example:

numbers = list()
i = 0
while (i <= 20):
    numbers.append(i)
    i = i+2
print(numbers)

This almost reads like regular English. Here’s how to parse it: while the numbers in a list are equal to or less than 20, we keep adding the number 2 to them and sticking them in a list. The “numbers.append(i)” line is what “appends” the numbers into the list. Once the numbers go over 20, the conditions have changed and we stop running the loop. We wind up with a list full of even numbers like so:

[0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20]

Easy, right?

But if you screw up, you can send your computer into a spasm of infinite loops.  I’ve unintentionally done it before. I was fortunate that someone had told me that that I could press Ctrl-C to stop the script and get out of the loop.

Let’s take a simple example of a ‘while’ loop::

loopy = 1
while loopy < 4:
    print (loopy)
    loopy = loopy + 1

This loops a few times and prints out the following:

1
2
3

BUT, if we had left out the last line of code, we’d be stuck in an infinite loop because 1 is always  less than 4.  So, the computer simply would not  know when to stop. Keep in mind that computers can do things very quickly, including things that you don’t want them to do (but unintentionally commanded them to do). An infinite loop is out-of-control code that can crash your computer. But, on the brighter side, at least you gain a deeper appreciation for that loopy symbol for infinity.

The symbol in several typefaces
https://commons.wikimedia.org/wiki/File:Infinity_symbol.svg

Featured image is Symbol used by Euler to denote infinity. Leonhard Euler - Variae observationes circa series infinitasCommentarii academiae scientiarum Petropolitanae 9, 1744, pp. 160-188.