mtWeb  Home > Python > Python TutorialSitemap  Search

Python Tutorial

Posted by martin on 25 Aug 2002.

Python is a high-level scripting language. This tutorial guides you through the process of downloading, installing, and running your first Python script.

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

comments
by deepu (deepuavesh@yahoo.co.in) on 10 Dec 2002 10:07am GMT

Good Help

C++
by krishna (naroulen@yahoo.com) on 12 Mar 2003 2:09pm GMT

Please help me tackling this problem.

#include <iostream.h>

int main ()

{

int c = 1;

// cout << "Enter numbers, terminated by a negative...\n";

while(c<8)

if(c%2==1)

cout<<(c+"Odd");

else

cout<<(c+"Even");

c++;

return 0;

}

Fix for yer CPP prob...
by RaWx (M477@Rock.com) on 17 Apr 2003 6:29pm GMT

I'm sure if the HTML is stripping your brackets, but if not, you should use them.

Also, I'm not sure if your cout commands are correct. I've never seen parantheses are incorporated or not, but I've never seen it.

Here's the same code, written in my 'coding style':

#include <iostream> // Most compilers use iostream asa pre-compiled header

int main()

{

int iC = 1; // Hungarian notation, yummy.

while (iC < 8)

{

if ((iC%2) == 1)

{

cout << iC << ": Odd" << endl;

}

else

{

cout << iC << ": Even" << endl;

}

c++;

}

return 0;

}

Hope that clarifies things for you, if not, e-mail me.

you sould really add this
by jeremy () on 10 May 2003 3:21am GMT

*if you use windows

if you use a migwin compiler such as dev c++ then add

#include <stdlib.h>

to the top of your source code and

system("pause");

to the end before return 0;

or if you use borland builder add

getchrar();

to the end befor return 0;

this pauses the system so you can see the what's in the window *if you use windows

not enough
by neo (deadganesh@deadman.com) on 7 Jun 2003 8:29am GMT

hi

man give more documentation

Setting up f2py for Windows
by Paule (paule@certrex.net) on 25 Aug 2003 7:47am GMT

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

user complains...
by () on 16 Oct 2003 9:15am GMT

I got an annoying javascript error when entering your site.

Rest of the site: Excellent!

HELP!
by newbie () on 21 Feb 2004 12:31pm GMT

i'm really new to pyrhon, just got it a few days ago, please tell me how to make a command. the commands to open another file. please help!

and by-the-way. this site is a huge help

python tutorials
by () on 15 Mar 2004 7:46am GMT

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

I ask help
by nasser (nasser@astro.rug.nl) on 15 Mar 2004 2:10pm GMT

How I can install Python on Crau Ve1

nice work
by vibe (truk@rediffmail.com) on 10 Apr 2004 6:33pm GMT

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

:-)
by Milen (milen@team.estreambg.com) on 14 Apr 2004 1:13pm GMT

mnogo dobre, Martinki :-)

File I/O for "newbie"
by Fin (crabman202002@yahoo.com) on 12 May 2004 1:45am GMT

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

can i get the updated version of python
by Sai Krishna P (krispee525@yahoo.co.in) on 2 Jun 2004 12:08pm GMT

I got all the points but i really need the updated version of python.

regrading python program
by nirmal barathi.b (nimmy_niso@rediffmail.com) on 15 Jun 2004 1:01pm GMT

sir iam new to python

so,i want more explination to python program

help
by sachin (sushil@servihoo.com) on 16 Jun 2004 6:45am GMT

I am new to python and I want to have the tutorials in pdf format.

hai...
by elly (kukun_oi@yahoo.com) on 16 Jun 2004 6:53am GMT

your situs is the best???

one question????

how to use fungtion Aunt in phyton language???? please give me exanple code

thank you

pls help write a simple python program by 7/5/04
by candice cammeray (chinkydiva@yahoo.com) on 2 Jul 2004 1:06am GMT

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.

:-)
by ossy (wormedup@yhoo.com) on 16 Jul 2004 10:04am GMT

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

thanx 1

Hey With this Python
by Unix \\ Us3R (flexible_budah@hotmail.com) on 8 Aug 2004 10:26pm GMT

This python program is there going to be a new release because i have enjoyed using the other versions they are very helpfull but i need to know WHEN IS THE NEW VERSION COMING OUT!!! .. Ty For the Help and Good Job on the Website.

shapes
by aman singh kamboj (ask502002@yahoo.co.in) on 23 Aug 2004 5:53pm GMT

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

"Houston, we have a problem here"
by gorm (hgorm@hotmail.no) on 26 Aug 2004 5:45pm GMT

I'm a newbie here, and did'nt get it. I think it would help me if the tutorial involved making one program, and explaining how, and why this and that is done. Explaining how a program starts, and ends, or whatever.

All I know is that I know precisely dick.

Thanx

data type of python
by mattaneeya (nompink@hotmail.com) on 4 Sep 2004 4:18pm GMT

send about information data type of python to me if someone know

i wonder.....
by alex (braintoxin@spymac.com) on 8 Sep 2004 2:54am GMT

i wish there's a e-book version of this stuff....or some thing that can be viewed offline.....;-)

changing line ending to Linux
by Bobby (fun3bobby@yahoo.com) on 23 Sep 2004 2:54pm GMT

Could you help me with the crlf.py script. I am trying to run it for a file but can't get it to do it. Any help wold be appreciated. Thanks

help me !!!
by howe (howe_lah@msn.com) on 7 Oct 2004 1:42am GMT

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

Hey?
by Joe (bondethan@hotmail.com) on 9 Oct 2004 2:31pm GMT

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.

teach me more
by hemanthnag (hemanthnag786@yahoo.co.in) on 12 Oct 2004 6:17pm GMT

i am new to programming script of python so teach me the basics of python

Poo
by Haakon Svendsen () on 17 Oct 2004 6:31pm GMT

I like to eat poo, nothing like the smell of poo in the morning!

Python
by Monkey (monkeyman23555@hotmail.com) on 19 Oct 2004 7:20pm GMT

Well ya i am also new to this script type so could some please teach me. My email is monkeyman23555@hotmail.com

howe's problem
by dbzs (adam2new@yahoo.com) on 25 Oct 2004 4:56pm GMT

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.

a good book
by nikhil (nsm.nikhil@gmail.com) on 8 Nov 2004 8:17am GMT

Here's a good python book.

www.python.g2swaroop.net

also i don't mean to insult the newbies or anything. But if u beg like please help me etc. then no one will help u. You should first do some research and come back.Also if u really wanna excel in programming you need to really love it & understand it. If u have an actual craving u will become good in no time.

Pthyon use
by Rishi kapur (rishi_19802001@yahoo.co.in) on 20 Nov 2004 8:22pm GMT

I am new the Pthyon, what is this language is this use for writing shell scripts or what

WHY IS PTHYON NOT SO POPULAR LANGUAGE
by Rishi kapur (rishi_19802001@yahoo.co.in) on 20 Nov 2004 8:27pm GMT

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

WHY IS PTHYON NOT SO POPULAR LANGUAGE
by Rishi kapur (rishi_19802001@yahoo.co.in) on 20 Nov 2004 8:30pm GMT

Hi,

Why is pthyon not so popular ,Is this language powerful and do some real stuff as compare to Perl.

Comment
by Spark (merispark@tele2.it) on 22 Nov 2004 6:14pm GMT

Lots of compliments for your very useful guide!

fire fire fire
by sid (sidvicious4u@yahoo.com) on 26 Nov 2004 11:41am GMT

Im really obsessed with fire but im way more interested in computers.I wanna learn how the stuff actually works now,i always used to mess around and explore on my computer.I bearly recently learned the many types of files,and got IZArc.I guess im a newbie at being a newbie but ill be back after i learn some more on my own....just....i wanna learn how to do stuff with my python thing,but im still on windows and i dunno im lost,cant really start and ive always had to settle for boredom and not having what my heart and mind desire.Always cuz they all got way better computers and im kinda poor,but i still wanna learn the basics so yea,this things taking too long im gonna stop typing and go learn,ill probably come back when i learn to converse with you ppl properly,l8es

python GUI's
by yoda (yoda_s10@yahoo.com) on 30 Nov 2004 8:29pm GMT

i am trying to make a game with a gui

but cant figure out how?

can you help

HELP ME
by Michelle (the_proud_family@yahoo.com) on 5 Dec 2004 2:20pm GMT

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

thanks you
by emra rachman setiawan (emra@hehe.com) on 5 Dec 2004 3:58pm GMT

dear,

i'm is beginner and i know about phyton

from steven haryanto (indonesian) and i very interesting about it. please give me more tutorial about phyton in the future if you have more.

thanks you.

emra rachman setiawan

Comment
by Prasad Bhatla (prasad_bhatla@telstra.com) on 16 Dec 2004 11:59am GMT

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.

i just don't know.
by ferris () on 19 Dec 2004 7:30am GMT

I have taken some vb classes in college. I have a little grip on it. I can see how the code works in your tutorials, but I could not make my code do anything on my linux laptop. Does this code need to be compiled? It would be a really good idea to have a background on the way that code must be written.

Also SID, get away from Microsoft Windows ASAP. It will hinder you from learning MAC and linux. Learn Linux first. I am using KNoppix. You can get a live CD, meaning that it will run your computer, without installing it. If you wish to install Linux... go with Ubuntu, or Knoppix. They are both based on Debian. Ubuntu is a Gnome desktop, Knoppix is a KDE desktop. Ubuntu will send you free CD's if you want one.

the site and oatmeal and dune
by Fear is the mind killer () on 19 Dec 2004 10:16pm GMT

yo yo cool site dawg

p.s. I WANT MY OATMEAL!!!!!!!!!!!!

and Dune is the best book eva!!!

a question about python
by Aerial (Skeon@msn.com) on 21 Dec 2004 3:46am GMT

Is python a piece of C/C++?

I need phyton installer
by aries (pegea57@telkom.net) on 28 Dec 2004 3:45am GMT

Thank's very much for your tutorials.

eng.
by raaki (happy_valentine205@hotmail.com) on 16 Jan 2005 7:13pm GMT

good i'm new to python but i get good introduction by u. thanks to u.

Help please
by Noremac on 29 Jan 2005 2:03pm GMT

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
by martin on 30 Jan 2005 1:51pm GMT

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.