Python Primer 3 – Loops and Conditions

This is my third post in a series to quickly introduce Python:

This part is probably the most difficult to understand, but it’s really what makes programming dynamic and powerful. Loops and conditions logic (and most programming logic, actually) resembles the way people think and behave. I’d say a loop is kind of like eating, execute the same “put into mouth” action while in the “hungry” state. Conditions are pretty much the same as anytime you say “if” in your daily life – if snow is on the road, stay home, otherwise (else) go to work.

If Statement

To illustrate iffing in Python, I’m going to use two built-in functions, len() and print(). len() simply gets the length of something and “returns” it (gives it back) to you, in the form of an integer (a number). print() just writes what you give it to the screen. In the interactive shell, print is usually assumed when you press enter but it’s more useful in a script (more on that later). Using the same colors list from the previous post, I’ll get its length and compare it to 2 (because I can) using the greater-than sign “>”, perhaps you remember that one from grade school.

colors = ["red","purple","blue"]
because_i_can = 2
if len(colors) > because_i_can:
    print("I've got lots of colors")
I've got lots of colors

Notice how the print part is indented. Python requires this to let the interpreter know that particular code is “inside” the if statement. Don’t forget the colon after your condition, Python gets mad.

If you change “because_i_can” to 3, they’re now equal and the print code doesn’t run. This is the nature of iffing – only run the code inside if the condition is true.

There’s lots more to if statements, like “elif” which is just another condition you can add to an if statement, and “else” which runs if none of the if conditions ran. You can look those all up on the official documentation, and probably guess their syntax. But the simplest form only uses one “if”. I use it all the time.

Loops

There’s really just two basic kinds of loops, “for” and “while”. Their logic is designed to resemble the English words from which their names are derived. For – “for each something in a group of somethings, do something”. While – “while in something is true, do something. Stop when it’s no longer true”. I personally don’t use while very much although it certainly has its use cases. I mostly find myself trying to slap some data around to get it to do what I want, so I use “for” loops quite a bit. I’ll start with that.

colors = ["red","purple","blue"]
for color in colors:
    print("I like "+color)
I like red
I like purple
I like blue

“color” is a temporary variable that is created on-the-fly as you write the for loop, and “colors” is the group of stuff that you want to go through. The cool part is I only had write my print() code once, but it was executed for each color in colors. Let’s combine it with an if statement to make it a little more fun:

my_favorite_color = "purple"
for color in colors:
    if color == my_favorite_color:
        print("Purple is my FAVORITE color.")
    else:
        print("I like "+color)
I like red
Purple is my FAVORITE color.
I like blue

A couple of new things here – “==” is used to compare two things and see if they’re equal. I also added an “else” part to my if statement. It runs if the “if” part doesn’t run.

“While” statements are nice if you want to run some code while a certain something is true. I was quite satisfied with my food example above, so we’ll run with that. Let’s say our stomach can fit 3 potatoes in it. We’ll add potatoes to our stomach until there are 3 in there:

potatoes_in_stomach = 0
while potatoes_in_stomach < 3:
    potatoes_in_stomach += 1
potatoes_in_stomach
3

“+=” is a handy way to say “add 1 to this variable”. So 1 was added until potatoes_in_stomach was no longer less than 3.

Built-in functions are cool, but next I’ll take a look at how to make a custom function.

Python Primer 1

This is my first post in a series to quickly introduce Python:

I use Python a fair amount. Anytime I want to tell the computer to do something really specific that isn’t accomplished easily in some off-the-shelf software, Python is my go-to. There are blogs, books, websites, and others that can explain all the amazing things that this cool programming language can do, but since I foresee using Python to illustrate other concepts that I’m trying to learn and understand, I’m going to try explain what I feel are the most important parts in the fewest amount of words. So on that note, here we go:

Getting Started

Most places start you off with some fancy development software called IDE (Integrated Development Environment) but I don’t really like those and I think it’s important to try the basics first and work up from there.

Microsoft Windows

You’ll want to go to https://www.python.org/downloads/windows/ Just go through the installer and you should be up and running.

Mac (OSX)

For an Apple computer same deal, just go to https://www.python.org/downloads/windows/ and install. OSX comes with Python 2 but not 3, unfortunately, so it has to be added.

Linux

If you are using Linux, you probably don’t need to be told how to do this, and listing all the ways to install software on the various major distributions is a waste of cyberspace. I use Ubuntu, it’s already installed.

Fire Up The Shell

The “shell” or command-line is basically just normal Python in slow motion, because we humans type commands slow. Here you can type in commands to the Python “interpreter” one at a time (you can also paste them in for faster results). Python is “interpreted” as opposed to “compiled” (like C++ or Java) because it converts the code you write to machine code when you run your program, instead of doing the conversion beforehand as with compilation. This approach has advantages and disadvantages, places where it’s useful and where it’s not. But the command line feature is great for testing since you can write your code and execute it right there by pressing enter.

On Windows, just search for Python and click on what you find. You’ll be at the right spot if your terminal window looks like mine below. On Mac and Linux pull up a bash terminal type “python3” and you’re off to the races.

Python 3 on Windows

What can you do from here? For starters it’s a great calculator:

Or you can use it to scare your co-workers on Halloween:

But you’ll probably want to do something a little more interesting. For that we’ll need some of the basics.

The Variable

It actually took me quite a while to realize that a variable is just a box in which you put something. Behind the scenes a variable is just some space allocated in memory for whatever data you want to store, but Python handles all of that messy stuff for you since it’s a relatively “high-level” language, meaning a lot of dealing with computer inner-workings like memory addressing and CPU instructions is handled for you so you can focus on getting the computer to do what you want. Not that you should avoid learning about that, but in a lot of situations this high-level approach lets you get things done a lot faster. In any case, just think of a variable as a cardboard box. You can put numbers (Python calls them integers) in a variable. Press enter after you’re done with a line:

x = 1
y = 2
z = 3

x, y, and z are just some variable names I picked that have no meaning, really. Use the “=” sign to put a value in your variable. Now you can reference the names in your code, and not the numbers:

x + y + z
6

You can re-purpose your variables by reassigning values to them:

x = "The quick brown fox jumps over "
y = "the lazy dog."
x + y
'The quick brown fox jumps over the lazy dog.'

The part between quotes “” is called a “string”, meaning alpha-numeric characters strung together. A string can be just one letter, one word, multiple words, multiple lines, it doesn’t really matter (I’ll quickly mention that strings can use single quotes or double quotes, doesn’t matter which).

But don’t try to add two variables that aren’t the same “data type”, like an integer and a string, because Python gets mad:

y + z
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: must be str, not int

Welcome to the world of errors, you’ll be seeing a lot of those.

Next up is some cool ways to organize your stuff, Python calls them Lists and Dictionaries. See you next time!