Super Simple Python Tutorial

A super simple tutorial about Python.

Variables

Variables are symbols that represent numbers or strings of letters. Here we assign a value of 5 to the variable myvar:

myvar = 5

To assign strings of letters and numbers (e.g., words, sentences, etc.), place them in single or double quotes.

myvar = "This is a sentence that I'm assigning to the variable myvar."

Variables can be manipulated with operators. Here the variable total is 5:

a = 3
b = 2
total = a + b

Here the variable sentence is “mooses are awesome”:

a = "mooses are "
b = "awesome"
sentence = a + b

This gives an error because it doesn’t make sense:

a = "mooses are "
b = 5
sentence = a + b
# What the heck, this doesn't even make sense?!?
# The str command converts the value of b (5) into a string representation ("5").
sentence = a + str(b)
# Now sentence is: "mooses are 5"

(Note that “comments,” or parts of your program that aren’t interpreted as code, start with “#”.)

Boolean variables are True or False.

a = True
b = False

They are especially useful when comparing other variables. Here are some examples:

a = 5
b = 6
c = 5
result = (a < b) # result is True
result = (a > b) # result is False
result = (a == b) # result is False; they are not equal
result = (a != b) # result is True; it is true that they are not equal
result = (a == c) # result is True; a and c are equal.
result = not (a == c) # result is False; a and c are equal (True), but "not" negates that (False).
result = not (a != c) # result is True.
# (It is false that a and c are not equal: False, they are equal. But "not" then negates that, so True.)

You can also combine these comparisons using logical operators like and and or:

alist = ["I", "am", "really", "nice", "right?"]
print alist[:3]
# Prints a list containing the first three elements: ['I', 'am', 'really']
print alist[-3:]
# Prints a list of the last three elements: ['really', 'nice', 'right?']
print alist[2]
# Prints the third element "really" (because in programming we start counting at 0, not 1!)
print alist[1:3]
# Prints a list containing elements from the second to the third letter: ['am', 'really']

Dictionaries

Sometimes rather than just listing variables (values), you want to be able to associate them with a lookup values (keys). In Python, this is accomplished with a “dictionary” (usually called an “associative array” in other languages). For example:

Why does “Done!” only appear once? How did Python know not to include print "Done!" in the “for loop”? It’s because of the indentation. print a_var is indented by four spaces under the for loop, so Python decided it should be placed in the loop. print "Done!" was not indented relative to the for loop, so it was “outside the loop.”

This code adds all the numbers from 0 to 4 and prints out the sum:

total = 0
for num in [0, 1, 2, 3, 4]:
total = total + num
print total
# Prints out 10

Lists of numbers are so common that Python has a special command to generate them: range. Range is a “definition” (called a “function” in other languages) that accepts three “parameters”: the number to start at, the number to end at (actually the number to end at plus one), and the difference between sequential numbers. This example should help:

total = 0
for num in range(0, 5, 1): # Remember, this is the same as [0, 1, 2, 3, 4]
total = total + num
print total
# Prints out 10

You can also use for loops to loop through dictionaries. In this case, it loops through the dictionary keys.

my_dog_dictionary = {"obedience": "never", "attitude": "defiant", "lazy": "ridiculously so"}
for key in my_dog_dictionary:
print key, my_dog_dictionary[key] # Since it loops through the keys, you can get the values too.

The above code block prints this to the screen:

lazy ridiculously so
attitude defiant
obedience never

While loops

While loops are also very useful. They continue to loop until some variable comparison evaluates to True.

t = 0
while (t < 4):
print t
t = t + 1 # So t increases by one every time it goes through the loop.

The output of the above code block would be:

0
1
2
3

If you want to break out of the loop early, use break:

t = 0
while (t < 4):
print t
t = t + 1 # So t increases by one every time it goes through the loop.
break
# Prints out only 0.

Beware of infinite loops. You’ll have to press control-C to break out of them:

while (1 == 1): # This is always true, so it will just keep printing the string below forever.
print "Keep printing this forever..."

Conditional statements

Often you only want to run a certain piece of code if certain conditions are met. Conditional if statements can be used for this purpose. Consider this code block:

Classes and Objects

Sometimes you want to group variables and definitions together in one “idea.” Imagine a scientist. She has certain characteristics (variables) and can perform certain actions (definitions). Let’s make a class to represent a scientist:

Notice that the first parameter in any definition contained within a class is always self. self refers to the class itself.

As I said, a class is just an idea. It’s like the outline of what a scientist could be. Let’s use this class to make actual scientists (at least in our computer). The actual scientists are “objects”, to use programming terminology.

Reading and writing files

As you see from the example above, a variable doesn’t have to be a number or a string. It can also be an object (i.e., a class made “real”). Files on the disk can also be objects. Just use the open command. It accepts two parameters: the filename, and the mode, where “w” means write to disk, and “r” means read from disk.

Suppose we have a file on the disk named “myinput.txt” that has the following contents:

Jacob
Jane
Bob
Fred
Darth Vader

Let’s open “myinput.txt” for reading (i.e., in “r” mode).

inp = open("myinput.txt", "r")

read will read the entire contents of “myinput.txt” as a single string.

Notice “\n” at the end of each item. That represents a newline character (when you press enter or return on your keyboard).

Let’s expand our program now, adding “is awesome” to each file line.

inp = open("myinput.txt", "r")
lines = inp.readlines()
inp.close() # Once you're done with your files, close them.
for line in lines:
# The "strip" command removes any spaces or newline characters at
# the beginning or end of the string.
print line.strip() + " is awesome!"

This little program prints the following to the screen:

Jacob is awesome!
Jane is awesome!
Bob is awesome!
Fred is awesome!
Darth Vader is awesome!

What if in addition to printing to the screen, we also saved the output to a file called “myoutput.txt”? Use the open command in the “w” mode (for “write” to disk).

inp = open("myinput.txt", "r")
lines = inp.readlines()
inp.close() # Once you're done with your files, close them.
outp = open("myoutput.txt", "w") # Here we're opening a new file object in write mode.
for line in lines:
# The "strip" command removes any spaces or newline characters at the beginning or end of the string.
print line.strip() + " is awesome!"
# Also write it to the disk. Notice that I'm putting "\n" on the end, because I want each
# declaration of awesomeness to be on a separate line in the file. This isn't necessary
# with the print command, because print automatically adds a "\n" to the end of strings.
outp.write(line.strip() + " is awesome!\n")
# Now we're out of the for loop, so we can close the output file too.
outp.close()

The above prints the same thing to the screen as before, but it also created a file called myoutput.txt that contains the following text:

Jacob is awesome!
Jane is awesome!
Bob is awesome!
Fred is awesome!
Darth Vader is awesome!

Manipulating strings.

There are many python definitions for manipulating strings. Since string manipulation is a common task, thought I’d give a few quick examples:

Conclusion

Python is a very powerful language, and we’ve barely scratched the surface of what it can do. There are many tutorials that cover more advanced topics on the web. I hope this gives you a good start. Best of luck!