Super Simple Python Tutorial

A super simple tutorial about Python.

No fluff, just for beginners.

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:

a = 5
b = 6
c = 5

result = (a == 5 or b > 8)  # True or False evaluates to True (logical "or" means "either or")
result = (a == 5 and b > 8)  # True and False evaluates to False (logical "and" requires that both be True)

Outputting to the screen

Nothing is actually shown on your screen when you run the above examples. The values are stored in memory. To “print” to your screen, use the print command:

a = "mooses are "
b = "awesome"
sentence = a + b
print sentence
# Now the words "mooses are awesome" actually show up on your screen.

Lists

Sometimes you want to store multiple values in one variables. You can create a list (called an “array” in most other languages), which is like a collection of other variables:

mylist = []

You can add things to the list using append:

mylist = []
mylist.append("hello")
mylist.append(5)
print mylist
# Prints ['hello', 5] to the screen

Notice that you can append different kinds of variables (e.g., a string and a number) to a list.

You can also define a list’s members right when you create the list:

mylist = ["hello", 5]

It’s also possible to combine lists:

list1 = [1, 5]
list2 = ["moose", 7]
list1.extend(list2)
print list1
# Prints [1, 5, 'moose', 7] to the screen

There are other ways to manipulate lists. Here are some examples:

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:

my_dog_dictionary = {}  # Makes an empty dictionary.
my_dog_dictionary["obedience"] = "never"
my_dog_dictionary["attitude"] = "defiant"
my_dog_dictionary["lazy"] = "ridiculously so"

print my_dog_dictionary
# Prints out {'lazy': 'ridiculously so', 'attitude': 'defiant', 'obedience': 'never'}

print my_dog_dictionary["lazy"]
# Prints out "ridiculously so"

You can also define the dictionary when you create it:

my_dog_dictionary = {"obedience": "never", "attitude": "defiant", "lazy": "ridiculously so"}

print my_dog_dictionary
# Prints out {'lazy': 'ridiculously so', 'attitude': 'defiant', 'obedience': 'never'}

Loops

For loops

Sometimes you want to consider all the members of a list one by one. “For loops” are great for that:

list_of_vars = [0, 1, 2, 3, 4]
for a_var in list_of_vars:
    print a_var
print "Done!"

The output of the above looks like this:

0
1
2
3
4
Done!

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:

print range(0, 5, 1)
# Prints [0, 1, 2, 3, 4]

print range(5, 10, 2)
# Prints [5, 7, 9]

print range(0, 100, 10)
# Prints [0, 10, 20, 30, 40, 50, 60, 70, 80, 90]

So let’s rewrite our previous code block using range:

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:

computers = ["mac", "linux", "windows"]

for computer in computers:
    if computer == "mac":
        print "Macs are good."
    elif computer == "linux":  # elif means "else if"
        print "Linux boxes are the awesomest!"
    else:  # "else" means none of the conditions above were met.
        print "Windows is lame."

The above code outputs the following:

Macs are good.
Linux boxes are the awesomest!
Windows is lame.

Definitions (functions)

What if you want to always perform a series of commands together? You can group them into “definitions” (called “functions” in other languages). Let’s put our adding code into a definition:

def add_numbers():
    total = 0
    for num in range(0, 5, 1):  # Remember, this is the same as [0, 1, 2, 3, 4]
        total = total + num
    return total

Notice that instead of printing total at the end, I’m “returning” total. The return command means, “This definition is done, and here’s a variable with the answer I got.”

How does Python know which commands belong to the definition, and which commands are outside it? Again, it’s all about the indentation (four spaces per indent).

Here’s how you can use (or “call”) a definition:

def add_numbers():
    total = 0
    for num in range(0, 5, 1):  # Remember, this is the same as [0, 1, 2, 3, 4]
        total = total + num
    return total

print add_numbers()
# Prints 10

print add_numbers()
# Prints 10

So whenever I call add_numbers(), I get 10 back.

I can make functions more useful by adding “parameters.” Consider this code block:

def add_numbers(min, max):  # The parameters are "min" and "max".
    total = 0
    for num in range(min, max + 1, 1):  # Using "max + 1" because range doesn't normally include the max itself.
        total = total + num
    return total

print add_numbers(0, 4)  # Add numbers in [0, 1, 2, 3, 4]
# Prints 10

print add_numbers(3, 6)  # Add numbers in [3, 4, 5, 6]
# Prints 18

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:

class Scientist:
    # Define some class variables with default values.
    name = "Jane"
    nerdinesslevel = 0
    social_skills = "antisocial"
    fashion_sense = "abysmal"

    # And also some class definitions
    def say_something(self):
        print self.name + " says: Science is awesome."

    def add_two_numbers(self, num1, num2):
        print "Scientists can totally add!"
        return num1 + num2

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.

class Scientist:
    # Define some class variables with default values.
    name = "Jane"
    nerdinesslevel = 0
    social_skills = "antisocial"
    fashion_sense = "abysmal"

    # And also some class definitions
    def say_something(self):
        print self.name + " says: Science is awesome."

    def add_two_numbers(self, num1, num2):
        print "Scientists can totally add!"
        return num1 + num2

jane = Scientist()

# This scientist's name is Jane, she's moderately nerdy,
# is very social, but has only moderate fashion sense.

jane.name = "Jane"
jane.nerdinesslevel = 5
jane.social_skills = "social"
jane.fashion_sense = "ok"

print "Jane's name is " + jane.name
# Prints out "Jane's name is Jane"

jane.say_something()
# Prints out "Jane says: Science is awesome."

print jane.add_two_numbers(1,2)
# Prints out "Scientists can totally add!" and then 3.

# The power of objects is that we can use them as a template
# to easily create additional scientists.

bob = Scientist()
bob.name = "Robert"
bob.nerdinesslevel = 10
bob.social_skills = "antisocial"
bob.fascion_sense = "excellent"

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.

inp = open("myinput.txt", "r")
text = inp.read()
inp.close()  # Once you're done with your files, close them.
print text

text is a single string, so the output looks like this:

Jacob
Jane
Bob
Fred
Darth Vader

(We’ve basically recreated the unix cat command using Python.)

Let’s rewrite this code using readlines, which will create a list of the file lines.

inp = open("myinput.txt", "r")
lines = inp.readlines()
inp.close()  # Once you're done with your files, close them.
print lines
# Prints out ['Jacob\n', 'Jane\n', 'Bob\n', 'Fred\n', 'Darth Vader\n']

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:

mystring = "   Hello dude. I am nice.   "

print "*" + mystring + "*"
# Prints '*   Hello dude. I am nice.   *' to the screen.

print "*" + mystring.strip() + "*"
# Prints '*Hello dude. I am nice.*' to the screen.

print "*" + mystring.lstrip() + "*"
# Prints '*Hello dude. I am nice.   *' to the screen.

print "*" + mystring.rstrip() + "*"
# Prints '*   Hello dude. I am nice.*' to the screen.

mystring = mystring.strip()  # So now the variable "mystring" is "Hello dude. I am nice."

print mystring.split()
# Prints ['Hello', 'dude.', 'I', 'am', 'nice.']

print mystring.split(".")
# Prints ['Hello dude', ' I am nice', '']

print mystring.rjust(50)
# Prints '                            Hello dude. I am nice.'

print mystring.ljust(50)
# Prints 'Hello dude. I am nice.                            '

print mystring.center(50)
# Prints '              Hello dude. I am nice.              '

print mystring[:3]
# Prints the first three characters, "Hel"

print mystring[-3:]
# Prints the last three characters, "ce."

print mystring[2]
# Prints the third letter "l" (because in programming we start counting at 0, not 1!)

print mystring[1:3]
# Prints from the second to the third letter, "el".

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!