Udacity CS 101: Procedures Part II

Now that you know what are procedures and how to make them, we’ll go through how to use them

def the_last_letter(s):

return s[-1]

welcome = "hello"

print the_last_letter(welcome)

The procedure described here basically takes a string named s as an input and returns the last letter of the string as the output.

When this program is fed into the Python interpreter, it is aware of the procedure, but does not execute. The procedure is basically a blueprint and does not activate on its own. What runs the procedure is the print statement.

When Python reaches the print statement, it sees that it will have to show the_last_letter(welcome) onto the console. It recognizes the_last_letter as a procedure that has been defined, and proceeds to evaluate it. The input to the_last_letter is the string "hello", and this string is passed into the procedure blueprint under the variable named s, which is why s[-1] works and will correctly evaluate to the letter 'o'. The procedure will output the letter 'o' in this case via the return statement. The return statement basically returns the program flow to where the procedure was initially started, and in this case it was in the print statement. Since the return statements states that it will output s[-1], the_last_letter("hello") is effectively replaced by s[-1], which is the letter 'o'.

At this point in time we must understand some important things, given the following program:

def the_last_letter(s):

return s[-1]

welcome = "hello"

print the_last_letter(welcome)

After running this program, the value of variable welcome will not change. Think of it this way, the value of welcome, which is the string "hello" is passed into the variable s. In other words, the variable s is assigned to a value of "hello". Hence if we add this statement at the end of the code:

print welcome

Python will still print "hello", and not "o". Also, if at this point of time you add the following statement:

print s

Python will give an error, saying that variable s is not known. You see, variables in procedures are by default only valid within the procedures. And since the_last_letter has already given an output via a return, it has exited. Hence the variable s no longer exist.

This Udacity post references Udacity CS 101 Unit 2 Chapters 7, 8, 9, 10, 11, 12, 13, 14 and 15.
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s