Learning Python
Contents |
[edit] What is Python?
Python is a powerful, dynamic, byte-code compiled, object oriented, interpreted language that has become extremely popular lately. It is used by Google, NASA, Argonne National Laboratory, Industrial Light & Magic, and many more. Python is included in most every Linux and Unix distribution, including Mac OS X.
- Easy to read Python code
- Easy to write Python code
- Fast to program in Python
- Python code is byte-compiled so it runs reasonably fast
- Cross platform (from cell phones to !BlueGene/L and everything in between)
- Open source with multiple implementations
[edit] Target Audience
This document is meant for people that already understand the basics of programming. It will help if you already know what a variable is, what conditional and branching statements are, and what functions and objects are.
This document is not meant to cover everything, just to give you a little taste of what Python has to offer and provide resources for you to learn more.
[edit] A Word on Whitespace
Python uses whitespace to know when code blocks begin and end, so make sure you use a consistent indentation style! This will become extremely important as you start working with branching, loops, functions, and classes. Just remember to always indent the same and try not to mix tabs and spaces.
[edit] Saving Scripts
You probably won't want to type everything in this tutorial, especially later for the more advanced topics. What you can do is create a new file and put code into it, make it executable and then run it from the terminal. This will also let you use your favorite text editor (I suggest gedit with the Tango theme). Please note the first line, it is very important that you put this line into all your Python files (it tells your terminal how to run the script, in this case through python)!
#!python #!/usr/bin/env python print "Hello, world!"
$ chmod +x myscript.py $ ./myscript.py
[edit] Jump In
Since you probably already know a bit about programming, the best way to learn Python is to just jump in! We are going to do just that. Open a terminal and type python, and you should see a prompt similar to the one below:
$ python Python 2.5.1 (r251:54863, Oct 5 2007, 13:36:32) [GCC 4.1.3 20070929 (prerelease) (Ubuntu 4.1.2-16ubuntu2)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>>
This is the interactive interpreter that lets you run Python code. Let's try a couple things in the interpreter. Type the following into the interpreter, one line at a time followed by pressing enter,
#!python print "Hello, world!" answer = 39 + 3 print answer
name = "Daniel" print "Hello, " + name + "!"
Congratulations, you now know how to print to the screen and how to assign variables. Since Python is dynamically typed there is no need to pre-declare variables and their types, just set a value and Python takes care of everything behind the scenes. You may also notice that handling strings in python is a breeze. Here are the built-in types that Python uses,
- int
- float
- string
- list
- tuple
- set
- dict
[edit] Working With Integers and Floats
Integers and floats are the basic units for storing numbers. They work just like in C/C++, however there is no set limit (other than the amount of memory you have) on the values that they can hold. Here are some examples you can try in the interpreter (ignore lines beginning with #, they are comments),
#!python # Math works just like you would think 1 + 2 + 3 / (1 + 1) 8 * 4 8 % 5
# Some examples with floats 1 + 2 + 3 / 2.2 84.5 * 26.5
[edit] Working With Strings
Strings in Python can contain characters, and there is no distinction made between single and multiple characters. Strings in Python are very easy to work with,
#!python # Creating strings first_name = "John" last_name = "Smith" # Concatenating strings name = first_name + " " + last_name print name # String slicing initials = first_name[0] + ". " + last_name[0] + "." print initials three = name[0:3] print three last_letter = name[-1] print last_letter # Common string functions num = str(23) "jack".capitalize() "one, two, three".split(", ") "foo bar baz".find("bar") len("This is a test string!")
[edit] Working with Lists, Tuples, and Sets
Lists, tuples, and sets are ways of grouping other variables. Lists, tuples and sets can contain any other objects. Sets are a little different from lists and tuples in that they contain only unique objects.
#!python # Lists mylist = [1, 2, 3, 4, 5, 4, 3] print mylist # Tuples mytuple = (1, 2, 3, 4, 5) print mytuple # Sets myset = set(mylist) print myset # Slicing works just like with strings print mylist[2:4] print mylist[-1] # Common sequence functions print len(mylist) print ", ".join(["one", "two", "three"])
[edit] Working with Dicts
Dicts (short for dictionary) are a type of object sometimes called an "associative list," where elements are associated with other values rather than just their position in the list. In Python, dicts are a sequence of key: value pairs. This is probably easiest to show in an example,
#!python # Create a dict grades = { "math": "B+", "csci": "A", "engl": "B" } # Picking a value is easy print grades["math"] # Adding new values is also easy! grades["musc"] = "C" print grades["musc"] # Common functions grades.keys() grades.has_key("musc")
[edit] Getting Input
There are several ways to get input into a Python program. You can read from the keyboard using the raw_input(prompt) command:
#!python name = raw_input("Enter name: ")
[edit] Program Logic
Python has if/else and looping statements just like most other languages. If you are used to C/C++ the for loop may throw you off a little.
#!python name = raw_input("Enter name: ") if name == "Daniel": print "Hey!" elif name == "Bob": print "Hello!" else: print "Go away!" for name in ["Kim", "Chris", "Alisha"]: print "Hello, " + name + "." for x in range(10): print x
[edit] File IO
File IO in Python is extremely easy. To open a file you use the open function. Files are opened for reading by default.
#!python myfile = open("example") for line in myfile: print line
Writing to files is just as easy,
#!python myfile = open("output", "w") myfile.write("This is an example line!\n") print >>myfile, "This is another way to write to files."
[edit] Functions
Functions are just like in other languages, but begin with the def keyword. By default they return nothing, but can return one or more values using the return statement.
#!python def hello(name): """ Print a simple hello to some name. """ print "Hello, " + name.capitalize() + "!" hello("Rob") hello("Jackie") # Default arguments def hello(name="world"): """ Print hello to a name if it is given, else say hello to the world. """ print "Hello, " + name.capitalize() + "!" hello() hello("Jim") # Returning stuff def coordinates(input) """ Split a string into two coordinates without error checking """ parts = input.split(", ") return int(parts[0]), int(parts[1]) x, y = coordinates("1, 2")
Those triple-quoted strings you see above is called docstrings. They describe what a function/method/class does and are used inside the interpreter to generate documentation for all your code using introspection. After defining the functions as above try issuing these commands:
help(hello) help(coordinates)
With all this you should now be able to write some simple programs!
[edit] Object Oriented Programming with Python
As mentioned before, Python is an object oriented programming language, and we have really just touched the surface of it by using existing objects. We will probably want to define our own at some point.
[edit] Classes
Classes are a way to define new objects in Python, similar to other languages including C++. Classes can have attributes and methods, and everything is public by default. Where in C++ you have an implicit this pointer for all classes, the Python philosophy is to keep things simple and not have magic variables that just exist in certain methods. What this means is you must pass a self variable to each method implicitly when defining the method. The names of built-in functions for Python objects typically use underscores (like the init constructor below):
#!python class Car: """ An object to hold information about a car, such as the make and number of doors. """ def __init__(self, make, doors=4): """ Initialize a new car instance given a make and optionally a number of doors. """ self.make = make self.doors = doors def info(self): """ Print information about this car to the screen. """ print "I am a " + self.make + " car with " + str(self.doors) + "doors." golf = Car("VW") golf.info()
[edit] Inheritance
Classes can inherit from one another, just like in C/C++. Python supports multiple inheritance, but for the sake of simplicity the example below will show single inheritance.
#!python # Assume the class Car is defined as above! class Golf(Car): """ An object to hold information about a specific car - a VW Golf. """ def __init__(self): # Call the parent class constructor on myself Car.__init__(self, "VW", 5) golf = Golf() golf.info()
[edit] Modules
Modules are a way to group functions, classes, and more. Modules are a good way to reuse code and as we will see the Python Standard Library consists of hundreds of modules. Creating your own modules is easy,
Save the following as mymodule.py
#!python def hello(name="World"): print "Hello, " + name + "!"
Execute the following in the same directory as mymodule.py
#!python import mymodule mymodule.hello()
You can also import items from a module's namespace into your own namespace,
#!python from mymodule import hello hello()
Modules can also contain multiple files. In this case, the module name will be the name of the folder containing the files, and a file called init.py must be present.
[edit] The Standard Library
The Python Standard Library is one of the features that makes Python so powerful. It is "batteries included" and for things that aren't included you can almost always find a module for it for Python these days. Using the standard library is easy,
#!python import sys import os print sys.argv print os.listdir(".")
There are many, many modules, and they are all documented on the Python Standard Library Reference.
[edit] References & Futher Reading
- http://www.python.org
- http://en.wikipedia.org/wiki/Python_(programming_language)
- http://docs.python.org/tut/tut.html Python Official Tutorial
- http://docs.python.org/lib/lib.html Python Standard Library Reference