Python Tutorial

Python is a somewhat unpopular language that is often compared to Perl (from people who know it exists). So what exactly is Python - it is a scripting language, this means it is interpreted rather than compiled, so it saves time during debugging and early development.

Python is a high level language - this means that you can write big programs very fast and easier than with low level languages like C/C++.

How do I get Python

You can download it for free from Python's website, it is Open Source so you can even modify it's source, at least if you know C. There is a source version and also precompiled binaries for both Linux and Windows.

How do I install Python

If you want to install the Windows version you just run the graphic installer and select some options. If you compile it for Linux/Unix you'll have to do the usual three steps to complete it:

./configure
make
make install

The last one usually requires to be run as root, you may also want to compile tk-inter support in, that's: ./configure --with-tk.

How do I run Python

If you want to check something simple run the Python interpreter by typing python or following a shortcut (Windows). The interpreter isn't very useful for large pieces of code so generally you would want to use your favorite text editor to create the scripts and then execute them.

How do I execute a saved script

This depends on your OS:

Linux/Unix
Put #!/usr/bin/env python at the top of the script and do chmod +x foobar.py. If you want to run the script as a CGI (from a webserver) you should better use #!/usr/local/bin/python or #!/usr/bin/python, depending on the system configuration.
Windows NT/2000
Run cmd.exe, if the .py extension is registered from the Python interpreter you can go with typing the filename.
Windows 9x/ME
Type python foobar.py if the python binary is in your path.

What editor do you use for writing the scripts doesn't really matter although one with syntax highlighting is preferred. I only know one editor for Windows/Linux: it is SciTE, and one which is Unix only - Kate or its predecessor KWrite (both bundled with KDE).

Enough talk, let's start coding

Only one thing before that in other languages statements are separated by braces and such - Python identifies statements by indentation only.

#!/usr/bin/env python

# This is a comment
# comments can span one line only

print 'Hello world!'
print "Hello world!"

You can delimit strings with single or double quotes - it doesn't make any difference to Python. If you want to write a string on more than one line you can escape the end of the line with a backslash:

foo = "I'm a very long string
	which spans multiple lines"
print foo

or use HereDoc syntax with """ or ''':

foo = """I am a really long
	comment but it doesn't
	matter no backslashes are
	needed
"""

You can also access directly single characters or slices from a string

foo = "Hello"
print foo[1] # outputs "e" since indexing starts at 0
print foo[1:] # ello
print foo[-1:] # o
print foo[2:4] # ll

Control structures

if 1 == 2 :
	print 'One equals two'
else :
	print 'One does not equal two'

As you have noticed no braces are used, just indent, this promotes readable code.

if 1 < 2 :
	print 'One is lesser than two'
elif 1 > 2 :
	print 'One is greater than two'

Loops

for i in range(0, 10) :
	if i % 2 == 0 :
		print i, 'is an even number'
	else :
		print i, 'is an odd number'

This example will loop through the numbers from 0 to 10 and test if the number is odd or even. The modulus operator (%) is used to calculate the remainder from dividing the number by two.

The same example can be rewritten also with a while loop.

i = 0

while i <= 10 :
	if i % 2 == 0 :
		print str(i) + ' is an even number'
	else :
		print str(i) + ' is an odd number'
	i += 1

i = 'Hello world'
print i

This example also shows that even though Python's variables are loosely typed (you can assign any type of data to a single variable), you have to convert them to a single type if you want to operate on different kind of variables.

To save the space that print adds between different parameters passed to it, you also have to add it to the string (when using string concatenation).

Command-line parameters

import sys

print sys.argv[0] # prints the filename of your script
print sys.argv[1] # and the first parameter
print sys.argv[1:] # or all parameters

If you want to pass parameters from the command line you will need the sys module, which is imported on the first line of the example. The module defines the argv list which contains the arguments to the script.

Lists in Python are something similar to arrays in other languages yet Python has arrays also, which are more functional than lists so if you want to use arrays you would have to import the array module.

Comments

Setting up f2py for Windows

Does anyone know how to set up f2py the Fortran95 to python wrapper generator to work properly under MS Windows 9x/XP?

python tutorials

the tutorials were very nice and perfect for Beginners but some extend it would be better if u add some more stuff some detail examples
thank u

nice work

u musta heard this a million times..............nice job done

File I/O for "newbie"

Not a bad site at all
#Write a file
#this opens a file named test.txt
#the string is written to the file then the file is closed
out_file = open("test.txt","w")
out_file.write("Write what you want inside here!\n")
out_file.close()
#Read a file
#open the same file, but read it this time
#read the file as string data
in_file = open("test.txt","r")
text = in_file.read()
#or text = in_file.readline()
in_file.close()
print text

pls help write a simple python program by 7/5/04

dear goodness i am in desperate help.
i need someone to help me write a simple program using python.
basically, the prog asks for an input of 2 colors, and the program will return both colors, but a range of 10 colors in between them.
so red and blue... return would be red and diffferent shades of red leading to blue.
plsplspls i desperate need your help, i have to have this done by Monday July 5th and i honestly have no idea how to even start using Python.
pls and thank you.
Candice.
just reply back to my email if you can help me.
thank you again.
chinkydiva@hotmail.com is my msn messenger.

:-)

very nice site. u doing a great job.just hope we can get extended 'free' tutorials for newbies .
thanx 1

shapes

how can i draw shapes using python and how a program is repeated.

help me !!!

can sombody tell me what's wrong with my python quiz script?...it doesn't print anything when i run it!! thanks.
score = 1
count = 0
while score != 1024:
count = count+1
if score == 1024:
print "you win!"

if count == 1:
print "which famous cosmologist is dying of a degenerative disease?"
print "a Stephen Hawking"
print "b Edward Hubble"
print "c Rupert Murdoch"
print "d Pope John Paul"
playeranswer = raw_input("answer: ")
answer = "a"
elif count == 2:
print "which country had the highest number of gold medals in the recent olympics?"
print "a China"
print "b Australia"
print "c USA"
print "d Korea"
playeranswer == raw_input("answer: ")
answer = "c"
else:
print score
if playeranswer == answer:
score = score*2
print "well done! your score is now $",score
..............................thanks

Graph package in Python

Hi,
i would like to know best graph package can be used with python..anyone with experience in using them please provide me details

chapagain, anish

Hey?

I'm completely new to this program (Python) and if someone could teach me some basic beginner code because I don't understand anything coded here :(
But if someone could teach me one on one that would be awsome.

howe's problem

hey, you may need to make the answer check for uppercase as well as lowercase.
P.S.
I'll get a book from a library and post a good file that outputs directory listings into an xml file, and maybe on to search the result xml file.

WHY IS PTHYON NOT SO POPULAR LANGUAGE

Hi,
Rishi this side, I just want to know why is pthyon not us popular , Is this language really powerful and do some real stuff as compare to Perl

HELP ME

HELP ME PLEASE!! my email is the_proud_family@yahoo.com
I can't get the ball to go up right side and then I need it to turn
around and keep turning until velocity=0 I have been at it for the
past 2 weeks now i give up and call for help. Please if anyone can
gide me through i will be so grateful!! I have pasted my code below
from cmath import *
from visual import *
floor1 = box(length=10, height=0.5, width=4, color=color.blue)
floor1.pos = (-6,4,0)
floor1.axis= (5,-5,0)
floor2 = box(length=10, height=0.5, width=4, color=color.blue)
floor2.pos = (6,4,0)
floor2.axis= (-5,-5,0)
floor3 = box(length=7, height=0.5, width=4, color=color.blue)
floor3.pos = (0,1.25,0)
ball= sphere(radius=0.5, color=color.red)
ball.pos=(-8.6,7.5,0)
m=3. #kg
angle=asin(3.6/5.)#radians
g=-9.8
mu=.2
N=mgcos(angle)
F=mgsin(angle)
f=mu*N
lax=(-Nsin(angle)+fcos(angle))/m
lay=(-Ncos(angle)-fsin(angle)+m*g)/m
rax=(+Nsin(angle)+fcos(angle))/m
ray=(-Ncos(angle)-fsin(angle)+m*g)/m
ds=0.01
dt=0.01
vx=lax*dt
vy=lay*dt
ball.velocity=vector(vx,vy,0)
#print a
while 1:
rate(100)
ball.velocity.x=ball.velocity.x+lax*dt
ball.velocity.y=ball.velocity.y+lay*dt
ball.pos=ball.pos+ball.velocity*dt
if ball.x>-3.5 and ball.x<=3.5:
vx=sqrt(2(-gball.y+0.5(vx2+vy2)-fds))
ball.velocity.x=ball.velocity.x+mugdt
ball.velocity.y=0
ball.pos=ball.pos+ball.velocity*dt
if ball.x>3.5 and ball.x<8.6:
vx=vx*cos(angle)
vy=sqrt(2/m(m-gball.y-fds))
#print vy
vy=vy*sin(angle)
#print vy
ball.velocity.x=ball.velocity.x+rax*dt
ball.velocity.y=ball.velocity.y+ray*dt
ball.pos=ball.pos+ball.velocity*dt
#print ball.pos

Comment

I am 50+ !!. Recently at work , I had the opportunity to develop a user interface for a keyboard intensive task-- like heaps of radio button groups- and interface to a Database.
Got my rusty programming skills oiled, and started off by doing a script in PerlTk. My Senior Tech suggested Python.
I chanced on your great intro site and you have another python convert !!!!
Keep up the good work.

Help please

PLEASE PLEASE PLEASE HELP ME! Is there anyway, with python or any other program to convert .exe files to a mac compatable format, or with python make .exe files run on a mac. Please email me!

Compiling Python

Hey Noremac, it's possible to compile python code. If you just want to run it on a Mac there's a python interpreter for Mac too.
If you really want to compile it see Compiling Python Code and HOWTO: Compiling Python Modules with MPW. AFAIK it's not recommended to compile Python yet.

hallo everybody,i am a computer student from greece.
I am new at Python programming and i want your help for this exercise:
Write a program which accepts as entry an odd number N (N>3) and it shapes below two forms. For example, the exit for N=5 should be:

+
+++
+++++
+++++++
+++++++++

and

+
+++
+++++
+++++++
+++++++++
+++++++
+++++
+++
+

my e-mail is ch.gol@hotmail.com.Send me there.Thank you

sorry,mistake with the shapes.The first is a triangle and the second one is a rhomb