Got Class?

On how to use classes in Python

Here are the metaphors I use to understand Python’s functions, modules, methods and classes:

Functions are like individual legos. Once you’ve created them, you can snap them in and out as needed to create working code.

Modules are sort of like prefab buildings that you have (or someone else has) built, in part, with those legos. You can add these entire prefabs to some larger construction project, or you can just scavenge some bits and pieces from a prefab and add it the construction project.

Modules are just Python files that contain relatively normal programs that are useful and can be utilized as often as you like. A module can have definitions of variables, functions, and even classes. You use “import” to bring modules – or pieces of modules – into whatever code you’re writing.

Methods are the same as functions, more or less. Except for the fact that they live “inside” classes. But, then, what in the heck are classes?

Classes are the blueprints, a metaphor I took from Steven Thurlow. He writes that a class “isn’t something in itself, it simply describes how to make something. You can create lots of objects from that blueprint – known technically as an instance.”

That sounds nifty, right? First you have legos, then prefabs made of legos, and then blueprints to keep it all organized.

Except this blueprint is also a bit like instructions that you put into a virtual 3-D printer. That is, the class both organizes and helps produce objects, all of which have similar characteristics and functions (or methods).

But enough metaphors for now. Let’s build a class, or draw a blueprint, or whatever works for you.

Step One: Decide what you want your overarching structure to cover. I’ve decided to build a dog, sort of.

Step Two: Next do the designing. In this case, we’re going to keep it somewhat basic but not so basic that you can’t see any nuances. The comments I’ve left explain how I see things.

Step Three: Create stuff (i.e., instances) based on your blueprint (i.e., class):

class Dog: #creates class called "Dog"

    def __init__(self, breed, height, weight, length, color):

        '''
        The code line above is a method common to classes. 
        Based on how you call the function, Python can 
        figure out what "self" is, so you don't need to 
        put it in among the parameters. You only need to 
        pass in the values called breed, height, weight, 
        length, and color
        '''
        self.breed = breed
        '''The line above makes sure that the program knows 
        that the value "breed" is going to be passed as 
        self.breed. Self is a placeholder for whatever 
        you decide to use. In this case, self is a 
        placeholder for 'Hank', as you can see below. The 
        same principle applies to the four other parameters 
        directly below'''
        self.height = height
        self.weight = weight
        self.length = length
        self.color = color
    def bark (self, sound):
        '''
        This adds a new method call "bark". When you call it, 
        it prints out whatever word you've put in as a parameter
        '''
        print (sound)
Hank = Dog('labrador', '24', '100', '36', 'yellow')
''' 
Here we are assigning the name Hank to Dog with these five values. As you can see, we don't need to put in a value for self. This is an example of how we are using a class to create an 'instance' named Hank. 
''' 

print("This is Hank's breed: " + Hank.breed + ". And here is his weight: " + str(Hank.weight)) 
print("Oh yeah, and here is his length: " + str(Hank.length)) 
''' 
In the lines above, we are printing out three specific values associated with Hank. This all hinges on what the blueprint describes in the class. We are putting some actual objects in based on that blueprint 
''' 

Hank.bark("bow wow") 
print("Really? Bow wow? You couldn't get more imaginative than that, you shmuck?") 
Hank.bark("How about wan-wan, as the Japanese dogs say?") 
''' 
Here we are calling the method of def bark(self, sound) in a couple of ways. 
'''

And here’s how this stuff prints:

This is Hank’s breed: labrador. And here is his weight: 100
Oh yeah, and here is his length: 36
bow wow
Really? Bow wow? You couldn’t get more imaginative than that, you shmuck? How about wan-wan, as the Japanese dogs say?

Okay, I think that’s about right. I should also mention that one class can inherit features from another class. It’s almost as if such classes are part of a family tree and they all share the same DNA/bloodline. But, if you’re a beginner, then your mind is probably already blown, so we won’t bother with inheritance for now.

PS –  However, if you want to learn more about classes and inheritance immediately, I can recommend the following sources of information:

An Introduction to Classes and Inheritance (in Python)

Sthurlow.com on Classes

Python from Scratch: Object Oriented Programming

Featured image: Hank by Cyndi Vickers

The ABCs of Python: “and,” “as,” “assert” and Stephen King

Let’s take it from the top. Alphabetically speaking, here are the first three keywords in Python:

and

Shocker! This pretty much has the same meaning as the English word and, aside from the all the Boolean logic stuff we discussed before. Bottom line: If you tell your program that it must have, let’s say, both a poncho and an umbrella before it takes some action, then it’ll take you very literally. Don’t expect it to do what you want without both of them. The code below uses and. Go ahead and run it your text editor. If that works, change the dog assignment to False and see what happens:

dog = True
cat = True
if dog and cat:
    print ("yep, you have a dog and a cat in your house")

as

The popular writer Stephen King has been known to pen books using the alias of Richard Bachman. Sometimes you’ll see this phrase: “Stephen King writing as Richard Bachman.” That’s pretty much the same way Python uses the word as. It creates aliases, especially for modules that you “import” into your code so you can use them without writing them from scratch.

Let’s take the example of the “turtle” module, which you can use it to draw pictures using, well, turtles. If you wanted to just use it, you could write “import turtle” to get started (we’ll talk more about import a little later ). But you could also give the turtle module an alias. Let’s say you want to give it the alias “slowOne” and then use the renamed “slowOne” module. Here’s how you might go about that.

import turtle as slowOne    # allows us to use the turtles library

wn = slowOne.Screen()     # creates a graphics window
alex = slowOne.Turtle()   # creates a turtle named alex
alex.forward(150)         # tells alex to move forward by 150 units
alex.left(90)             # turns by 90 degrees
alex.forward(75)          # completes the second side of a rectangle

Feel free to play around with the module for a bit. For a tutorial on how to use it, I recommend the chapter “Python Turtle Graphics” in the interactive version of the book How to Think Like a Computer Scientist.

assert

This handy, dandy keyword helps you discover whether or not you’ve written buggy code. You assert that something is true. If it is, nothing happens. No news is good news. If it’s not true, however, it gives you an “AssertionError.” What’s more, you can add your own verbiage to the assertion error. Run the following code in your text editor and you’ll see what I mean:

#this code uses "assert" and produces an AssertionError
x = 100
assert x < 2, "the value of x is just too big, dude"
Featured image: Stephanie Lawton - https://www.flickr.com/photos/steph_lawton/7634622516/ https://en.wikipedia.org/wiki/Stephen_King#/media/File:Stephen_King_-_2011.jpg

How Many Words Are in Pythontongue?

On using keywords in Python

If we’re just counting so-called keywords, then there really aren’t a lot to learn in Python. Things change over time as new versions of Python appear, but by my count and at the time of this writing, there are only 35 key words. So take heart, newbies, this definitely ain’t Mandarin.

Clywd-Powys Archaeological Trust, Rod Trevaskus
https://commons.wikimedia.org/wiki/File:Medieval_-Key(locking)_(FindID_249113).jpg

In fact, as a beginner who is taking tutorials, you’ll regularly use only about half those words. Still, I suspect that if you learn them all now, you’ll become a better coder faster (advice I wish someone had given me before I began my inefficient perambulations through Python coding). They don’t call them keywords for nothing.

So let’s start with an alphabetical list:

  1. and
  2. as
  3. assert
  4. async
  5. await
  6. break
  7. class
  8. continue
  9. def
  10. del
  11. elif
  12. else
  13. except
  14. False
  15. finally
  16. for
  17. from
  18. global
  19. if
  20. import
  21. in
  22. is
  23. lambda
  24. None
  25. nonlocal
  26. not
  27. or
  28. pass
  29. raise
  30. return
  31. True
  32. try
  33. while
  34. with
  35. yield

Not too intimidating, right? Easier than memorizing the school play you were in elementary school (unless, of course, you played the tree, my personal fav).  Now that you know what the keywords are, you need to know what they all mean and can do. That’s where the next series of blog posts come in.

PS – If you want to know more about keywords right now, I highly recommend Programiz’s Description of Keywords in Python with examples.

Is Khristmas in Your Dictionary?

On how to use Python dictionaries

So, we’ve talked a little about tuples (which use parentheses) and lists (which use square brackets). Now let’s talk dictionaries, which use those cute little curly brackets — that is {} — that come standard on keyboard but that you’ve probably never used unless you happen to be a mathematician.

Here’s your chance to put those curly brackets (sometimes called braces) to work. In Monty Python’s Bookshop Sketch, a customer comes in looking for various books, including “A Khristman Karol” and “Knickerless Knickleby.” Alas, the peeved Proprietor has never heard of them, at least not with those spellings.

But, with Python, we can easily enough create a dictionary in which those titles actually exist. Python’s dictionaries represent a kind of baroque list using the curly braces. These fancy lists are totally mutable and typically jam-packed with pairs of stuff called “items.” An item includes a key and a corresponding value or, to put it in plainer English, a name and some data you want to store along with the name.

So, let’s build a quick list based on the Bookshop Sketch. These are titles of books followed by the names of their authors:

Monty_Python_Library = {'Thirty Days in the Samarkind Desert \
with the Duchess of Kent': 'A. E. J. Eliott', 'David \
Coperfield': 'Edmund Wells','Knickerless Knickleby': \
'Edmund Wells', 'A Khristman Karol': 'Edmund Wells', \
'Rarnaby Budge': 'Charles Dikkens', 'Karnaby Fudge' : \
'Darles Chickens', "Olsen's Standard Book of British Birds: \
 Expurgated Version" : 'Olsen','Ethel the Aardvark goes \
Quantity Surveying' : 'Anonymous'}

Each book and its associated author is placed in a string, and a colon is used to connect them. If you don’t want to do all that typing, you can paste that into your text editor.

Note that I’ve added backslashes (\) to the code so that it can be broken into multiple lines and still run. Those backslashes are not part of the dictionary code. If you remove all the backslashes but put all the code onto a single line, it’ll still work. Now add the following:

print (Monty_Python_Library)

Run those the dictionary code and the print statement and you’ll see the entire dictionary appear in your IDLE Shell. So, that’s easy enough to create (I hope). It’s also easy to add or subtract things from that dictionary. Here’s how you add something:

Monty_Python_Library ['The Gospel According to Charley Drake'] = 'Charley Drake'

Now, if you print the library again, you’ll see the classic by Charley Drake added in.

Here’s how the code looks in my IDLE, though note I’ve added some extra print lines to make it a bit clearer:

But what if you want to get rid of some items? There are a couple of common ways of doing that as well. One uses the term del (as in delete), and the other uses the term pop (as in stick a needle in a balloon). We’ll use both below:

del Monty_Python_Library ['Thirty Days in the Samarkind Desert 
with the Duchess of Kent']
Monty_Python_Library.pop ('Rarnaby Budge')

If you print the dictionary again, those should be missing from the list.

You can now use this dictionary to find out who wrote specific titles. For example, we can use the following line to ask who wrote ‘David Coperfield’. We get, of course, the not-so-renown (except among Monty Python fans) Edmund Wells.

>>>Monty_Python_Library ['David Coperfield']

'Edmund Wells'

If you wanted to expand this library, you could add in more corresponding values to the titles, stuff such as publication date, publishing house, etc.

Monty_Python_Library ['David Coperfield'] = 'Edmund Wells', 'Random House', 1876

Here’s how this coding looks in my IDLE:

There’s plenty more to know about compiling and structuring dictionaries, but that’s enough to cover the basics. If you’ve suddenly developed a passion for dictionaries (and who hasn’t, at some point?), then I recommend the following sources:

Learn Python the Hard Way

Hands-On Python Tutorial

Feature Image: Duchess_of_Kent,_2013 wikimedia The Duke and Duchess of Kent; Image by Carfax2 in Wikimedia https://commons.wikimedia.org/wiki/File:The_Duke_and_Duchess_of_Kent,_2013.JPG

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.

Why Do Indents Make Deep Impressions?

On how to use indents in Python

Programs generally get written in blocks of code. A lot of programming languages use braces to indicate where a block starts and stops. Python doesn’t. It uses indents, sort of like paragraphs in English.  It’s more elegant than brackets, but if you don’t get the indents right, Python will torment you in a way your fifth-grade English teacher never could.

Let’s start with something simple.

Here’s a quick example of how indents can make a difference.

def indentsReallyMeanSomething():                       #Line 1
    print('Which line should print first?')             #Line 2
    print('This line or that line?')                    #Line 3
indentsReallyMeanSomething()                            #Line 4
print('It depends-how do you want to indent your code?')#Line 5

If we leave the indents as they look above, then we get a print out like this:

Which line should print first?
This line or that line?
It depends-how do you want to indent your code?

Now, we can take the indent out of Line 3 so the code looks like this:

def indentsReallyMeanSomething():                       #Line 1
    print('Which line should print first?')             #Line 2
print('This line or that line?')                        #Line 3
indentsReallyMeanSomething()                            #Line 4
print('It depends-how do you want to indent your code?')#Line 5

Then we get a print out like this:

This line or that line?
Which line should print first?
It depends-how do you want to indent your code?

I’ve set this code up so it works fairly well either way, but that’s not usually going to be the case. You might really screw things up by writing code that puts the wrong line first. Imagine telling a customer to check out before he or she even buys your product (doh!), or imagine telling someone to drive left and then right when you really mean to tell them to drive right and then left (WTF?).  Bottom line: the beauty of indents is more than skin deep when it comes to Python.

As a beginner, you should know a couple of more things about indents. First, the huge role that indents play in Python is pretty unusual in the world of programming languages. A lot of Pythonistas argue that it’s a graceful way of telling the computer which coding statements you want grouped together, a process sometimes referred to as “scoping.”

Not everybody is enamored with indentation, however. In fact, it’s one of the more controversial aspects of the language.  Andy Buckley, for example, wrote a blog post in 2007 called “Python indentation considered boneheaded.” He argues, among other things, that:

If more than one person, with different editor settings with regard to tab/space indentation edits the same Python code, a mix of spaces and tabs is pretty much guaranteed. In any other language, this doesn’t affect the bvehaviour of the code: in Python the invisible markup can completely change the logic. Oops.

Such complaints are one reason for the Python Style Guide. I should note that indenting with four spaces is the preferred indentation method in Python. Python 3 actually disallows mixing tabs and spaces for indentation in one piece of code.

As a beginner, I love the look of Python code, which has to be presented well in order to work. On the other hand, I’ll tell you that getting indents right has been one of the hardest things for me to learn.

But, to be honest, correctly using brackets might have proven just as hard. My issues probably have much more with my own boneheadedness than the boneheadedness of the language.

Feeling Loopy Yet?

On how to use loops in Python

It’s hard to do much coding without getting loopy. There are  reasons for that. First, we tend to use computers to do the same or similar tasks over and over, which is great because they don’t get bored (yet).

Second, loops allow your computer to go back to the same useful functions and plug in different values based on things such as input from human beings.

Third, loops help you write programs that go through long strings and lists of data one at a time (though incredibly quickly) to make decisions about them or otherwise use them.

Without loops, most programs would run for a split second and be done. So, loops are good –unless they’re bad — and when they’re bad, they can be very, very bad (play spooky foreshadowing music here).

Python has a simple and elegant loop system. There are really two kinds of loops, or three if you count nested loops (where you have loops within loops):

‘for’ loops
‘while’ loops
 nested loops

Let’s start with the “for” loops. Some programmers swear by them.  In one of the first books I read, Python in a Day, Richard Wagstaff notes, “I almost always use only the ‘for’ loop.” That’s largely because avoiding while loops reduces the risk of getting stuck in infinite loops.

“For” loops work in a number of ways. Here’s an example that uses a short list:

for number in [1, 2, 3]:
    print(number)
    print("Nobody expects the Spanish Inquisition! " * number)

Here’s what happens when you run this program:

1
Nobody expects the Spanish Inquisition!
2
Nobody expects the Spanish Inquisition! Nobody expects the Spanish Inquisition!
3
Nobody expects the Spanish Inquisition! Nobody expects the Spanish Inquisition! Nobody expects the Spanish 
Inquisition!

We multiply the number of times we say this classic Monty Python quip by the numbers in the list (oh yeah, although you probably know this already, the symbol * means multiplication in Python). When I started with Python, it took me awhile to figure out that the most important two words in such code are the most innocuous ones: “for” and “in”.  In Line 1 above, the word “number” has no particular importance. If I substituted the word “tomcat” or “aluminium” or “jigglywiggly” for the word “number,” the code would work exactly the same way. Quite often, programmers just use the letter i as the stand-in. It’s quick and dirty but definitely doesn’t stand for “imagination.”

All Python really “knows” is that you want to do something a certain number of times, depending on what’s in the list.  Think of it as your idiot savant bro, ala Rain Man. It’s excellent at counting and listing, not so hot at nuance.

Let’s put the “for” loop at the heart of a new function, like the one below. We’ll get super corny and jump with both feet into a dog metaphor.  We’ll name this function LassTheTailWagger.  We feed that function treats, which are in the parenthetical maw of our parameter. For every batch of treats she eats, she wags her tail, thus giving us the total number of all the treats.

(Note: If you try this at home, don’t forget to put the indents in the right place. They make all the difference, as we’ll see in our next post)

def LassTheTailWagger(dog_treats_she_eats):
#Returns the sum of the numbers treats eaten, according to wags of tail
    sumOfWags = 0
    for number in dog_treats_she_eats:
        sumOfWags = sumOfWags + number
    return sumOfWags

print(LassTheTailWagger([5, 3, 2, 7]))

At first, there are zero wags but, as we feed her treats, the sum of all the wags continues to climb. In the first loop, we feed her 5 treats (based on the list of numbers in the print line), and the SumOfWags equal 5. The code runs and then we loop the next number in the list (3) up into the code. It adds 5 and 3. The loop continues to run until we get to the last number in the list (7). At that point, we have fed her 17 treats and the program stops running.

If this is still confusing to you, the beginner, don’t worry about it. You’ve probably got the general idea, and it’ll become clearer as you learn more about coding in general and Python in particular. Keep in mind that playing around and repetition are the keys to learning. So, my advice is to play around with simple “for” loops for your own amusement until you’ve gotten the hang of them.

PS – If you want more tutoring on “for” loops, I recommend you try out the following: Python 3 Video Tutorial – For Loops

Featured image from Author User:Coaster J From https://commons.wikimedia.org/wiki/File:Blue_fire_loop.jpg

Could You Pass the Delicious-Looking Plate of Parameters?

More on Python functions, parameters, values and stuff

Last time around we started chatting about functions: that is, the legos of the Python universe. You always start a function with the word “def” followed by the name of the function, followed by parentheses and a colon. In other words:

def NameOfFunction ():

Sometimes there will something inside the parentheses. If so, that’s your “parameter.” In the world of Python, parameters and arguments are pretty much used interchangeably, but, technically, parameters are the variables and arguments are the values you give those variables.

If I write “height = 6,” then height is the variable and 6 is the value.

Anyway, a parameter sits beside the function and is often integral to the work it does, sort of like the chocolate chips in a cookie batter. To get an idea of how this works, check out the super simple code below. In this case, the name of the function is “theBatter” and the name of the parameter is “chips.” :

def theBatter(chips):
    return (chips)

All this does is crank out chips. That is, it cranks out whatever string is placed into parentheses next to the name of the function. I say that it “cranks out” but you don’t actually see the chips that it cranked out unless you tell Python to print them.

How to explain this? Let’s say somebody asks you to calculate 2 + 2. You do it in your head but don’t say anything. The answer is “returned” in your head. Then the person asks you to write the answer down. So you do, printing out “4”.

That’s how it works in Python in this case. Once the function runs, it “returns” the answer but the answer remains in Python’s “mind.” You don’t see the answer till you tell it to print.

Now, let’s actually use (or “call,” as they say) the function described above a couple of times and print out the results:

firstVision = theBatter ('Envision this string as filled with chocolate chips and being poured into batter')
secondVision = theBatter ("Not enough chips yet? That's okay. Pour this string of chips into the function as well")
print (firstVision)
print (secondVision)

Note that we placed a literal string of characters that discussed chocolate chip cookies between the parentheses. If you run this code, here’s what you should get:

Envision this string as filled with chocolate chips and being poured into batter

Not enough chips yet? That’s okay. Pour this string of chips into the function as well

Okay, now let’s do something moderately harder. Write this into a new program.

pecans1 = 50
pecans2 = 150
chips1 = 60
chips2 = 120
def yumFactor (ingredient1, ingredient2):
     total = ingredient1 + ingredient2
     return total
todaysCookies = yumFactor(pecans1, chips2)
tomorrowsCookies = yumFactor (pecans2, chips1)
print ("The yum factor for today's cookies is " + str(todaysCookies))
print ("The yum factor for tomorrow's cookies is " + str(tomorrowsCookies))

So, what’s happening here?

First, we assign some values to some variables. For example,  pecans1 is a variable that has a value of 50.

Second, we write a function called yumFactor. It takes two parameters: ingredient1 and ingredient2. All the function really does is add the values of those two parameters together and then give you the sum total.

Third, we “call” the function twice. The first time, we used two arguments: pecans1 and chips2. The second time, we used two other arguments. In both cases, we assign a name to the outcomes. Those names are “todaysCookies” and “tomorrowsCookies.”

Fourth, we print out those outcomes within the larger context of a string. What we actually get in the Shell are the following  two sentences:

The yum factor for today’s cookies is 170
The yum factor for tomorrow’s cookies is 210

(In case you couldn’t tell, I’m a fan of cookies.)

Here’s how all the code looks in IDLE before we run it:

And here’s what prints out in your Shell:

PS: Sometimes I  think of functions as dogs and parameters as dog biscuits (you can see that I tend to be drawn to food-related metaphors). You “call” the dog and give her some nice parameters to work on. She gobbles them up, “passing” them right through the body, building strong bones and teeth, as the commercials say. Of course, if we take the metaphor too far, I guess it means that our functions ultimately pass stuff that we have to pick up with plastic bags in the park. Metaphors are dangerous that way.

PPS: If you’re looking for a more sensible tutorial on functions, here’s one you might try.

Featured image from Andrew6111. Wikimedia Commons. https://commons.wikimedia.org/wiki/File:Plate_of_chocolate_chip_cookies,_ready_to_munch.jpg

Um, What’s Your Function, Again?

On a first look at functions in Python

Everybody needs to find a place in this world, and that includes your computer code.  One of the best ways of making sure your code knows its proper place is by writing it in the form of a function.  A function is kind of like a lego block. You write it in such a way that it can connect up nicely with other functions and lines of code. Together, they build something cool.

These structured blocks of code are used to perform an action and return some type of value.  They’re modular, so you may be able to use them over and over. In fact, Python has lots of built-in functions, such as the “print” function, designed to make your life easier. You take its built-in blocks and snap them together with blocks of your own design.

It’s sort of like child’s play, but with more cursing.

You know a function when you see one because it starts with the keyword known as “def,” which stands for “define.” That is, you immediately define what your block of code does. It’s sort of like those nametags at business conferences: “Hi, I’m So-and-So, and Work at NameOfBiz as a NameOfOccupation.” Except functions somehow seem a lot less lame than nametags.

Function blocks start with def and then are followed by function’s name, parentheses and a colon (don’t forget the colon!). Like so:

def function_name():

But that’s not all, there’s more! A lot more, as you’ll see in the next post.

PS – If you’re the instant gratification type and want to learn more about functions right now, then here are some sites I recommend:

Featured image from GTurnbull925. Wikimedia Common. https://commons.wikimedia.org/wiki/File:Pile_of_lego_blocks.jpg

When Does Your Code Get Iffy?

On using conditional if-else statements in Python

We live in a contingent world. That’s why it’s so hard to make predictions with any accuracy. Are you going to live in your current house for the next ten years? Well, that depends. If  we don’t inadvertently produce more kids and if we can afford to add on a new adults-only bathroom and if my boss doesn’t continue to drive me bonkers and if interest rates continue to climb like kudzu and if… Well, you get the idea. It’s all about how various conditions shape up.

Programmers need to worry about lots of contingencies as well. That’s why, in the world of programming, we have “conditional statements.” That’s usually just a fancy name for lines of code that begin with the world “if.” The programmer has to work out the possible conditions in advance.

Let’s say you want to write a program that automatically gives people their horoscopes. Well, that horoscope will be contingent on what year the person was born, what time they were born, what hour they were born, whether Venus was in retrograde (whatever that even means), etc. In short, there are a whole lot of “ifs” here.

Let’s start at a basic level. Write the following short code in a text editor and run it. (Don’t forget the indents because Python is extremely sensitive to those, which is a subject for another post!)

height = 8
if height == 8:
     print ("Hiya, Charlie! Nice stilts!")
 else:
     print ("Hey, Charlie, no stilts today?")

You should get the message, “Hiya, Charlie! Nice stilts!” Now, go ahead and assign the variable “height” to a smaller value such as 5 or 6 and run the code again. Because the condition of height changed, you got a different response. Such is the power of “if” and it’s sidekick  “else”.  If you can master “if,” you can prepare your code for a world in which conditions change and the future always looks iffy.

PS – If you want more information on conditionals, I recommend the Hands-on Python Tutorial.

Featured image from Tall Camp. Author Jennifer Morrow from San Francisco. Wikimedia Commons.