For Loop

It’s time for an awesome part of Python. Python’s for loops are pretty amazing compared to some other languages because of how versatile and simple they are. The idea of a for loop is rather simple, you will just loop through some code for a certain number of times. I won’t get a chance to show you the flexibility of the for loops until we get into lists, but sure enough its time will come. Onto an example:

Example
for a in range(1,3):
    print (a)
Result 1
2

First, print is indented for a reason. Remember that Python is picky about spacing. It is somewhat complicated to understand exactly what a is in the example. In this instance, a is a variable the increments itself every time we run through the loop. Next, we use the range keyword to set the starting point and the point right after we would finish. This is precisely why the number 3 didn’t print. Python is quite fond of this idea of all the way up to a number, but not including it.

Also, notice the in keyword. This is actually part of the for loop and you will understand it a bit better after we deal with lists and dictionaries. So, basically the above for loop says, “For variable a, which will be incremented at the end of every loop, in the range of 1 up to 3.”

While Loop

While loops in Python can be extremely similar to the for loop if you really wanted them to be. Essentially, they both loop through for a given number of times, but a while loop can be more vague (I’ll discuss this a little bit later). Generally, in a while loop you will have a conditional followed by some statements and then increment the variable in the condition. Let’s take a peek at a while loop really quick:

Example
a = 1
while a < 10:
    print (a)
    a+=1
Result 1
2
3
4
5
6
7
8
9

Fairly straightforward here, we have our conditional of a < 10 and a was previously declared and set equal to 1. So, our first item printed out was 1, which makes sense. Next, we increment a and ran the loop again. Of course, once a becomes equal to 10, we will no longer run through the loop.

The awesome part of a while loop is the fact that you can set it to a condition that is always satisfied like 1==1, which means the code will run forever! Why is that so cool? It’s awesome because you create listeners or even games. Be warned though, you are creating an infinite loop, which will make any normal programmer very nervous.

Where’s the do-while loop

Simple answer, it isn’t in Python. You need to consider this before you are writing your loops. Not that a do-while loop is commonly used anyway, but Python doesn’t have any support for it currently.

Lists

We don’t have arrays; we have Python lists. Lists are super dynamic because they allow you to store more than one “variable” inside of them. Lists have methods that allow you to manipulate the values inside them. There is actually quite a bit to show you here so let’s get to it.

Example
sampleList = [1,2,3,4,5,6,7,8]
print (sampleList[1])
Result 2

The brackets are just an indication for the index number. Like most programming languages, Python’s index starting from 0. So, in this example 1 is the second number in the list. Of course, this is a list of numbers, but you could also do a list of strings, or even mix and match if you really wanted to (not the best idea though). Alright, now let’s see if we can print out the whole list.

Example
sampleList = [1,2,3,4,5,6,7,8]
for a in sampleList:
    print (a)
Result 1
2
3
4
5
6
7
8

I told you we would come back to see how awesome the for loop is. Basically, variable a is the actual element in the list. We are incrementing an implicit index. Don’t get too worried about it. Just remember we are cycling through the list.

Common List Methods

There are number of methods for lists, but we will at least cover how to add and delete items from them. All of the list methods can be found on Python’s documentation website. Methods follow the list name. In the statement listName.append(2), append() is the method.

  • .append(value) – appends element to end of the list
  • .count(‘x’) – counts the number of occurrences of ‘x’ in the list
  • .index(‘x’) – returns the index of ‘x’ in the list
  • .insert(‘y’,’x’) – inserts ‘x’ at location ‘y’
  • .pop() – returns last element then removes it from the list
  • .remove(‘x’) – finds and removes first ‘x’ from list
  • .reverse() – reverses the elements in the list
  • .sort() – sorts the list alphabetically in ascending order, or numerical in ascending order

Try playing around with a few of the methods to get a feel for lists. They are fairly straightforward, but they are very crucial to understanding how to harness the power of Python.

Dictionaries

Python’s dictionaries are not very common in other programming languages. At least at first, they don’t appear normal. Some super variables like lists, arrays, etc, implicitly have an index tied to each element in them. Python’s dictionary has keys, which are like these indexes, but are somewhat different (I’ll highlight this in just a second). Partnered with these keys are the actual values or elements of the dictionary. Enough with my terrible explanation, let’s go with an example.

Example
myExample = {'someItem': 2, 'otherItem': 20}
print(myExample['otherItem'])
Result 20

See, it’s a little weird isn’t it? If you tried to be an overachiever, you might have tried something like print(myExample[1]). Python will bite you for this. Dictionaries aren’t exactly based on an index. When I show you how to edit the dictionary, you will start to see that there is no particular order in dictionaries. You could add a key: value and, it will appear in random places.

A big caution here is that you cannot create different values with the same key. Python will just overwrite the value of the duplicate keys. With all of the warnings aside, let’s add some more key:values to our myExample dictionary.

Example
myExample = {'someItem': 2, 'otherItem': 20}
myExample['newItem'] = 400
for a in myExample:
    print (a)
Result newItem
otherItem
someItem

Isn’t that crazy how dictionaries are unordered? Now, you might not think they are unordered because my example returns alphabetical order. Well, try playing around with the key names and see if it follows your alphabetical pattern. It won’t. Anyways, adding a key:value is really easy. Simply put the key in the brackets and set it equal to the value. One last important thing about dictionaries.

Example
myExample = {'someItem': 2, 'otherItem': 20,'newItem':400}
for a in myExample:
    print (a, myExample[a])
Result (‘newItem’, 400)
(‘otherItem’, 20)
(‘someItem’, 2)

All we did here was to spit out our whole dictionary. In lists when we told Python to print our variable out (in our case, it’s a), it would print out the value. However, with dictionaries, it will only print out the key. To get the value, you must use the key in brackets following the dictionary’s name. Dictionaries are a little confusing, but they are well worth your patience. They are lightning fast and very useful after you start using them.

Formatting

We waited a little bit to talk about formatting because it might get a little intense with how much you can do and how easily you can do things with variables in Python. Formatting in Python is a little bit odd at first. But, once you get accustomed to it, you’ll be glad you did.

Formatting Numbers as Strings

Example
print('The order total comes to %f' % 123.44)
print('The order total comes to %.2f' % 123.444)
Result The order total comes to 123.440000
The order total comes to 123.44

Ya, I told you it’s a little weird. The f following the first % is short for float here because we have floating numbers and Python has a specific way of dealing with formatting decimals. The left % tells Python where you want to put the formatted string. The value following the right % is the value that we want to format. So, Python reads through the string until it gets to the first % then Python stops and jumps to the next %. Python takes the value following the second % and formats it according to the first %. Finally, Python places that second value where the first % is. We can use a single value such as a string or a number. We can also use a tuple of values or a dictionary. Alright, this is great, but what about formatting strings?

Formatting Strings

Strings are just like how we were formatting the numbers above except we will use a s for string instead of an f like before. Usually, you will only want to format a string to limit the number of characters. Let’s see it in action:

Example
a ="abcdefghijklmnopqrstuvwxyz"
print('%.20s' % a)
Result abcdefghijklmnopqrst