Python is an object orientated, interpreted language created by Guido van Rossum. Python interpreters are available for most operating systems. Python applications can be compiled and packaged into stand alone programs and interpreted on a web server to create web applications similar to PHP or ASP.
For this tutorial I’m going to go through the basics of installation on a windows machine, installation in a web browser, performing command line string manipulation, dealing with date and time, arithmetic and interacting with input and output on the command line.
Getting Started – Installation
Installation of python on Windows is extremely simple visit the Python Download Repository and pick a copy of the Python Windows Installer. For this tutorial I will be using Python version 2.7.1 primarily due to the number of supported libraries and functions. Run through the installation process as you would with any other installer, Voila instant Python.
Installing Python in Apache
If you would like to use Python to build web application you’ll need to enable Python in Apache. You can do this by following these instructions.
If you downloaded Python 2.7.1 the installation location will be C:\Python27.
#!/Python27/python print 'Content-type: text/html' print '' print '' print '' print 'Hello.' print ''
Save this file as test.py to your htdocs folder under your apache installation directory and run!
Programming Python on the Command Line
First bring up the Python Shell located at C:/python27/python.exe. This is were we can execute instructions directly into the Python interpreter via shell.
Save this file as test.py to your htdocs folder under your apache installation directory and run!
Let’s go ahead and write our first instruction, type the following command:
print "Hello World"
The Shell should return simply “Hello World”.
Importing Python Modules
Before we continue, I’d like to quickly explain how the Python Standard Library works. When you need to access a specific module within the library you need to perform the following command;
import libraryName
Simply exchanging libraryName for the module name you wish to import.
Dealing with Variables and Strings in Python
Next lets create a variable or two and manipulate the strings with Pythons built in functions.
#Importing the string module import string tutorial = 'a crash course in python' #capitalize the string tutorial.capitalize() #UPPERCASE the entire string import string string.upper(tutorial) #Concatenate a string print tutorial = tutorial + ' for beginners' #contactonate and redeclare the variable tutorial = tutorial + ' for beginners' #strip the new concatonation tutorial.replace(" for beginners","")
For more fun with strings in Python look at the string class.
Dealing with Dates and Times in Python
Next lets use the datetime module from the python standard library.
import time #lets get the UNIXTIMESTAMP or seconds from epoch which is 1/1/1970 00:00:00 import time time.time() #Days since epoch time.time()/(60*60*24) #3 ways to print the current date in human readable format print time.asctime(time.localtime()) print time.ctime(time.time()) print time.ctime() #find the timezone of the server time.timezone #GMT time since epoch time.gmtime()
Python Control Flow
Python’s flow control includes for loops, while loops and conditional branches. Branches is a new term for me and is simply another way of saying conditionals.
var1 = 100 if var1: print "1 - Got a true expression value" print var1 else: print "1 - Got a false expression value" print var1 var2 = 0 if var2: print "2 - Got a true expression value" print var2 else: print "2 - Got a false expression value" print var2
Loops in Python
Below is a standard ‘for’ loop which iterates over an expression. Using the range function to control the number of iterations before terminating the loop. With ‘I’ variable auto incrementing over each loop until the expression validates to true.
for i in range(1, 5): print i else: print 'The for loop is over'
Another example of a for loop in python using the ‘in’ operator
for letter in 'Python': # First Example print letter
Next up is the while loop.
count = 0 while (count < 9): print count count = count + 1
Handling Lists, Tuples and Dictionaries in Python
Python offers four ways in which to arrange data, Lists, dictionaries and tuples. I’ll discuss each along with sample code.
Python Lists
Creating a list in Python is much like creating an array in PHP or C++. To print a list you can simply access the number of the storage ID just like a dimensional array. Or specify to arguments x:x. In the examples below it will print 1 thru 4.
list1 = ['bob', 'dave', 'john', 'Jane','Daniel']; list2 = [1, 2, 3, 4, 5,]; print "list1[0]: ", list1[0] print "list2[1:4]: ", list2[1:4]
Python Dictionaries
Python Dictionaries are similar to key and value arrays in that you specify the key name linked with a value.
person = {'Name': 'Katie', 'email': 'katie@myemailaddress.com', 'Age': '25'}; print "person['Name']: ", person['Name']; print "person['Age']: ", person['Age']; print "person['Email']: ", person['Email'];
Python Tuples
In Python Tuples are essentially lists and operate in a similar way but cannot be changed. The Python documentation refer to Tuples as Immutable, hence cannot be changed.
tup1 = ('Katie', 'katie@myemailaddress.com', '26'); tup2 = (1,2,3,4,5,6,7); print "tup1[0]: ", tup1[0] print "tup2[1,4]: ", tup2[1,4]
Creating Python functions
Below is code for building a Python function, printing from the function and declaring the function with an argument.
def printString( str ): #function code is printed here with arguments passed to the function. print str return; printString("Let's print this out!");
Now you should be able to work with python on the command line and parse Python code within a webserver.