A Basic Introduction To Python 3

A while back I was introduced to what has become my #1 favorite programming/scripting language: Python. It’s difficult for a language developer to come up with something that’s both powerful and easy to write, something that flows naturally and allows you to focus on what’s important in your code. Python does this beautifully. It makes just the right kinds of assumptions, allowing you to focus more on what your program should do instead of exactly how it should be done. There’s no worrying about memory management, variable typing, or those blasted semicolons, you just keep your mind on the logic of your application.

Python takes some pretty big departures from some of the more traditional languages like C/C++, fitting in better with the dynamic languages like Ruby, Smalltalk, and even Javascript. The ability to quickly and easily finish complex tasks in Python has even been the subject of some great web comics.

Note – Python is an interpreted language, the interpreter can be downloaded here. All examples in this guide are written for Python 3.0 which is NOT fully backward-compatible with prior versions. If you’re having trouble running the examples, check your Python version.

Running the examples

I’ll include various examples throughout this guide. Once you’ve got the Python 3 interpreter installed (make sure it’s Python 3), code can be run in two ways:

Script file

You can copy/paste the complete text of the example code into a text file. Python files typically end in .py. Open your command prompt and run the Python executable followed by the name of the file. On my Linux machine, I run:

python3.0 myfile.py

This should be roughly the same on Windows and Mac as well, though you may have to specify the full path to the Python interpreter, such as

C:\Python30\python.exe myfile.py

Interactive Interpreter

Python can also be run in interactive mode, where you can type in commands one at a time to see how it responds. This can be very useful in troubleshooting, or in trying out new things. Run the Python executable on its own, without any script file, and it will open up the interactive prompt.

Python interactive interpreter

Ctrl-D will exit the interpreter.

Whitespace

One of the most unusual aspects of Python is its use of whitespace to indicate blocks of code. Instead of begin and end, or grouping by brackets, Python uses the amount of indentation to tell how to handle blocks of code for looping and such. To many people coming from other programming languages, this seems like insanity. Once you get used to the idea, however, it becomes quite natural and forces your code to be clear and readable. We all indent code blocks anyway (or at least should) so it just makes sense for the language to understand that statements all lined up together are part of the same block.

As an added benefit, Python is not picky about just how much you like to indent, or even whether you prefer tabs or spaces. You can use a tab, a space, two spaces, 137 spaces, Python doesn’t care. All you need to do is be consistent. It will check your code and see “The first code block is indented by 4 spaces, so I’ll assume each other block is indented by another 4 spaces” or whatever the case may be. As long as you’re consistent in the way you indent your code, Python is flexible enough to understand. The following example may help clear things up.

1
2
3
4
5
x = 0
while x < 10:
    print(x)
    x += 1
print("All done")

Code Breakdown: The while loop tells Python to run the following block of code as long as certain conditions are true. In this case, the condition is that x is less than 10. It will continue to loop over that block until x hits 10. The “x += 1″ translates to “x = x + 1″ or “make x larger by 1″. Notice the final line does not get run until the while loop is finished. Python sees the indented lines, and treats those as the group of code to be run on each trip through the while loop. The final line is not indented with the others, so Python does not act on it until the while loop is finished.

Dynamic Typing

Python does not require you to define what type of data will be in a variable. You can put an integer, a string, a decimal, anything you want into a variable without having to tell Python what it is. Python will figure out, based on what you assign, what type of data that variable should hold. The following example should demonstrate:

1
2
3
4
5
6
7
8
x = 0
print("x is a: ",type(x))
x = 3.14
print("x is a: ",type(x))
x = "Hello"
print("x is a: ",type(x))
x = [1,2,3,4]
print("x is a: ",type(x))

Which gives us the output below

Example of Python's dynamic typing

Data Structures

The three data structures you’ll most commonly use in python are

  • Lists
  • Tuples
  • Dictionaries

Lists

are a lot like arrays in some other languages. They’re a one-dimensional sequence of items (though technically you can give them as many dimensions as you like). Each item in that list can be changed, moved, and removed at will without having to recreate the list, and without causing any change to the other items. Lists can contain any Python object, whether it be a number, a string, even other lists. The following code shows some basic usage of lists.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#create a list with a few sample items
myList = [1,2,3,4,5]
 
#len() gives a count of how many items our list holds
print("myList has ", len(myList), " items.")
 
#The items in a list don't have to be of the same type
myList.append("six")
myList.append("seven")
myList.append(8)
 
#We've appended three new items to the end of the list
print("myList now has",len(myList), " items.")
 
#Now let's see item number 0 (first item)
print("first item:", myList[0])
 
#and now the fourth item
print("fourth item:",mylist[3])
 
#Then pop the last item out of the list
print("and ends with" , myList.pop())
print("myList now has",len(myList), " items.")
 
#And see what we've done
print("The complete contents are:", myList)

Tuples

I won’t be covering tuples much, as they won’t be used it our example program and they’re similar to lists in many ways. Tuples, like lists, are a series of items grouped together. The difference is that tuples are not mutable. You cannot make in-place changes to the items in a tuple, you must re-create the tuple. This means no “append” or “pop” or other things that directly make changes to the contents of the tuple. If it helps, you can think of tuples as a read-only list (though that’s really not very accurate).

Dictionaries

These, I love. When I was first taught about dictionaries, I remember thinking something along the lines of “Well.. I GUESS that could be useful… sometimes”. Within a week, I used them every chance I got.

In Python, dictionaries are key:value pairs. It’s kinda like a list except that each item has two parts, a key and a value. In the following example, I’m going to make a dictionary to hold information about myself.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
myDict = {}
 
#       Key             Value
myDict["Name"]       = "Josh"
myDict["Occupation"] = "Computer Geek"
myDict["FavFood"]    = "Hani Special (no lettuce)"
myDict["FavBand"]    = "Anything but the B-52s"
myDict["Heroes"]     = "Tom Waits, Kurt Vonnegut, SpaceBat"
myDict["FavNumber"]  = 3.141592
myDict[42]           = "It's also a good number"
 
print("My name:",            myDict["Name"])
print("My heroes:",          myDict["Heroes"])
print("My favorite number:", myDict["FavNumber"])
print("What do I think of 42?", myDict[42])
print()
# Now I'll change my favorite number without creating a
# whole new dictionary
myDict["FavNumber"] += 100
print("My NEW favorite number:",myDict["FavNumber"])

A few things should be clear from the example. First, dictionaries can mix and match data of any type. Your keys and values can be of anything. You can even get really crazy and put things like functions inside dictionaries, but that’s way beyond the scope of this guide.

Second, dictionaries are mutable. You can add and remove items on the fly without recreating the dictionary or affecting other items.

If you’re still not sure of the usefulness of dictionaries, consider using them to track a user’s settings. You could have a dictionary called settings and store things like username, ip address, and screen resolution. Any time you need to reference that data, you can just pull it from settings[“username”], or whatever other key you’ve specified.

Bring it all home

Now we’re going to get to the real action, creating a useful Python 3.0 program. What this program will do is take a number representing money, and tell you how much pocket change would make that amount. It’s a pretty common coding exercise and is a good way to demonstrate the concepts we’ve covered so far.

I should tell you now that this program is NOT going to be written in the “best” way, my aim is to write it using the most basic concepts and operations possible. There are several “better” ways to write this, such using functions and the modulus operator, and including error checking, but this version should be pretty easy to understand.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
#Get the cash amount
total = input("Enter cash amount in dollars:  $")
 
#Reading from text input assumes text, so convert
#to decimal and multiple by 100 so we can count pennies
#(simpler math that way)
pennies = float(total) * 100
 
#create dictionary to hold our change values
change = {"quarters" : 0,
          "dimes"    : 0,
          "nickels"  : 0,
          "pennies"  : 0}
 
#Loop until all money has been accounted for
while pennies > 0:
  #Subtract each coin from the total, add 1 to count
  #for each coin, and restart loop after counting
  if pennies >= 25:
    change["quarters"] += 1
    pennies -= 25
    continue
  elif pennies >= 10:
    change["dimes"] += 1
    pennies -= 10
    continue
  elif pennies >= 5:
    change["nickels"] += 1
    pennies -= 5
    continue
  else:
    change["pennies"] = int(pennies)
    pennies = 0
 
#Finally, print our results
print("Q:",change["quarters"])
print("D:",change["dimes"])
print("N:",change["nickels"])
print("P:",change["pennies"])

Code Breakdown: We’re using input to get an amount of money in from the command line. Python assumes that what is being entered is a string of text, as opposed to a number, so we’ve got to tell it to convert that input into a usable number. We could have left the number alone (ie 15.95) but instead we converted it to pennies (multiplying by 100) to make the maths simpler so we wouldn’t have to worry about decimal points.

Next, we create a dictionary to hold the results of our computing. If this were a more complex program, we could pass that dictionary around to our functions, classes, etc without worrying about keeping track of separate variables for each type of coin.

After that comes the real work – the act of splitting our money total into individual coins. This program uses a while loop to keep cycling until we have no money left from our original input. Each trip through the loop looks at the amount of money, subtracts the largest coin it can, and restarts the loop. Instead of doing subtractions over and over, this program would likely be much more efficient if we had used the modulus operator, but the subtraction is easier to understand.

Once we’re finished with the loop, all that’s left to do is display our results.

Python is capable of FAR more than I could possibly cover here, but I hope I’ve been able to demonstrate the basics of how it works, and how it can be used to quickly and easily create tools that would be much more complicated in a less intuitive language.

In case anyone is as curious as I was about how to properly pronounce “tuple”, I was fortunate enough to have the opportunity to ask Guido van Rossum himself if it was “toople” or “tupple”, and he gave the somewhat unsatisfying answer “It’s whatever you want.”