Revision of Learn Python in 10 minutes from Sat, 14/01/2006 - 16:04

Preliminary fluff

So, you want to learn the Python programming language but can’t find a concise and yet full-featured tutorial. This tutorial will attempt to teach you Python in 10 minutes. It’s probably not so much a tutorial as it is a cross between a tutorial and a cheatsheet. I assume that you are already familiar with programming and will, therefore, skip most of the non-language-specific stuff. The important keywords will be highlighted so you can easily spot them.

Properties

Python is strongly typed (i.e. types are enforced), dynamically, implicitly typed (i.e. you don’t have to declare variables), case sensitive (i.e. var and VAR are two different variables) and object-oriented (i.e. everything is an object).

Syntax

Python has no mandatory statement termination characters and blocks are specified by indentation. Indent in to begin a block, indent out to end one. Statements that expect an indentation level end in a colon (:). Comments start with the pound (#) sign and are single-line. Values are assigned with the equals sign (”=”), and equality testing it done using two equals signs (”==”). You can increment/decrement values using the += and -= operators respectively. This works on many datatypes, strings included. For example:

intMyVar = 3
intMyVar += 2
intMyVar -= 1
strMyVar = "Hello"
strMyVar += " world."

Data types

The data types available in python are lists, tuples and dictionaries. Sets are available in the sets library. Lists are one-dimensional arrays (but you can have lists of lists), dictionaries are associative arrays (a.k.a. hash tables) and tuples are immutable one-dimensional arrays. The first item in all array types is 0. Negative numbers count from the end towards the beginning, -1 is the last item. Variables can point to functions. The usage is as follows:

lstSample = [1, ["another", "list"], ("a", "tuple")]
lstList = ["List item 1", 2, 3.14]
lstList[0] = "List item 1 again"
lstList[-1] = 3.14
dicDictionary = {"Key 1": "Value 1", 2: 3, "pi": 3.14}
dicDictionary["pi"] = 3.15
tplTuple = (1, 2, 3)
fnVariable = len
>>> print fnVariable(lstList)
3

You can access array ranges using a colon (:). Leaving the start index empty assumes the first item, leaving the end index assumes the last item like so:

lstList = ["List item 1", 2, 3.14]
>>> print lstList[:]
['List item 1', 2, 3.1400000000000001]
>>> print lstList[0:2]
['List item 1', 2]
>>> print lstList[-3:-1]
['List item 1', 2]
>>> print lstList[1:]
[2, 3.14]

Strings

Its strings can use either single or double quotation marks, and you can have quotation marks of one kind inside a string that uses the other kind (i.e. “He said ‘hello’.” is valid). Multiline strings are enclosed in triple double (or single) quotes (”“”). Python supports Unicode out of the box, using the syntax u“This is a unicode string”. To fill a string with values, you use the % (modulo) operator and a tuple. Each %s gets replaced with an item from the tuple, left to right, and you can also use dictionary substitutions, like so:

>>>print "Name: %s\nNumber: %s\nString: %s" % (class.name, 3, 3 * "-")
Name: Poromenos
Number: 3
String: ---

strString = """This is
a multiline
string."
""

# WARNING: Watch out for the trailing s in "%(key)s".
>>> print "This %(verb)s a %(noun)s." % {"noun": "test", "verb": "is"}
This is a test.

Flow control statements

Flow control statements are [while], [if], and [for]. There is no select; instead, use if. Use for to enumerate through members of a list. To obtain a list of numbers, use range(<number>). These statements’ syntax is thus:

lstRange = range(10)
>>> print lstRange
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
for intNumber in lstRange:
    # Check if intNumber is one of
    # the numbers in the tuple.
    if intNumber in (3, 4, 7, 9):
        # Break terminates a for without
        # executing the "else" clause.
        break
    else:
        # The "else" clause is optional and is
        # executed only if the loop didn't "break".
        pass # Do nothing

if lstRange[1]  2:
    print "1  2"
elif lstRange[2]  3:
    print "3  4"
else:
    print "Dunno"

while lstRange[1]  1:
    pass

==

Functions

Functions are declared with the “def” keyword. Optional arguments are set in the function declaration after the mandatory arguments by being assigned a default value. For named arguments, the name of the argument is assigned a value. Functions can return a tuple (and using tuple unpacking you can effectively return multiple values). Lambda functions are ad hoc functions that are comprised of a single statement. Arguments are passed by value. For example:

# arg2 and arg3 are optional, they have default values
# if one is not passed (100 and "test", respectively).
def fnMyFunction(arg1, arg2 = 100, arg3 = "test"):
    return arg3, arg2, arg1

ret1, ret2, ret3 = fnMyFunction("Argument 1", arg3 = "Named argument")

fnVariable = lambda x: x + 1
>>> print fnVariable(1)
2

Classes

Python supports a limited form of multiple inheritance in classes. Private variables and methods can be declared by adding at least two trailing underscores and at most one leading one (e.g. “__spam”). We can also assign arbitrary variables to class instances. An example follows:

class MyClass:
    def __init__(self):
        self.varMyVariable = 3
    def fnMyFunction(self, arg1, arg2):
        return self.varMyVariable

    # This is the class instantiation
>>> clsInstance = MyClass()
>>> clsInstance.fnMyFunction(1, 2)
3

# This class inherits from MyClass. Multiple
# inheritance is declared as:
# class OtherClass(MyClass1, MyClass2, MyClassN)
class OtherClass(MyClass):
    def __init__(self, arg1):
        self.varMyVariable = 3
        print arg1

>>> clsInstance = OtherClass("hello")
hello
>>> clsInstance.fnMyFunction(1, 2)
3
# This class doesn't have a .test member, but
# we can add one to the instance anyway. Note
# that this will only be a member of clsInstance.
>>> clsInstance.test = 10
>>> clsInstance.test
10

Exceptions

Exceptions in Python are handled with try-except [exceptionname] blocks:

def fnExcept():
    try:
        # Division by zero raises an exception
        10 / 0
    except ZeroDivisionError:
        print "Oops, invalid."

>>> fnExcept()
Oops, invalid.

Importing

External libraries are used with the import [libname] keyword. You can also use from [libname] import [funcname] for individual functions. Here is an example:

import random
from time import clock

intRandom = random.randint(1, 100)
>>> print intRandom
64

File I/O

Python has a wide array of libraries built in. As an example, here is how serializing (converting data structures to strings using the pickle library) with file I/O is used:

import pickle
lstList = ["This", "is", 4, 13327]
# Open the file C:\file.dat for writing. The letter r before the
# filename string is used to prevent backslash escaping.
flFile = file(r"C:\file.dat", "w")
pickle.dump(lstList, flFile)
flFile.close()

flFile = file(r"C:\file.txt", "w")
flFile.write("This is a sample string")
flFile.close()

flFile = file(r"C:\file.txt")
>>> print flFile.read()
'This is a sample string'
flFile.close()

# Open the file for reading.
flFile = file(r"C:\file.dat")
lstLoaded = pickle.load(flFile)
flFile.close()
>>> print lstLoaded
['This', 'is', 4, 13327]

Miscellaneous

  • Conditions can be chained. 1 < a < 3 checks that a is both less than 3 and more than 1.
  • You can use del to delete variables or items in arrays.
  • List comprehensions provide a powerful way to create and manipulate lists. They consist of an expression followed by a for clause followed by zero or more if or for clauses, like so:

lst1 = [1, 2, 3]
lst2 = [3, 4, 5]
>>> print [x * y for x in lst1 for y in lst2]
[3, 4, 5, 6, 8, 10, 9, 12, 15]
>>> print [x for x in lst1 if 4 > x > 1]
[2, 3]
del lst1[0]
>>> print lst1
[2, 3]
del lst1

Epilogue

This tutorial is not meant to be an exhaustive list of all (or even a subset) of Python. Python has a vast array of libraries and much much more functionality which you will have to discover through other means, such as the excellent online book Dive into Python. I hope I have made your transition in Python easier. Please leave comments if you believe there is something that could be improved or added.

Update: This article has been Dugg. Please post a comment here if there is anything else you would like to see, (classes, error handling, anything).

sign

it's VENI,VIDI,VICI. ;)

Submitted by Vaquerito (not verified) on Mon, 16/07/2007 - 07:11.
Re: sign

I know :)
---
Vidi, Vici, Veni.

Submitted by Stavros on Mon, 16/07/2007 - 08:26.
...

poor guy, so many stupid people picking on you...
how about Veni Veni Veni!!! ....or Vici Vici Vici!!!

Submitted by Anonymous (not verified) on Wed, 21/01/2009 - 14:54.
Unsure about 2nd example.

On the second example/snippet I got an error. That's because 'list' was not declared right? When I changed it to "mylist" I got the result '3' like your example. Or is that supposed to an example where we substitute it with any of the list types?

>>> myfunction = len
>>> print myfunction(list)
3

Submitted by Ravi (not verified) on Sat, 21/07/2007 - 11:51.
Re: Unsure

Yes, I'm sorry. You are, of course, correct. That should read "mylist", I have changed it.
---
Vidi, Vici, Veni.

Submitted by Stavros on Sat, 21/07/2007 - 15:29.
Line missing example 7 (Classes)


# This variable is shared by all classes.
>>> classinstance2 = MyClass()
>>> classinstance.common
10
>>> classinstance2.common
10

before classinstance.common there should be a line above it delcaring a common variable for the class. It's currently missing(cause I got an error without it):

MyClass.common = 10

Submitted by Ravi Chhabra (not verified) on Thu, 26/07/2007 - 09:47.
Re: Line

The "common" variable is declared in the class declaration above...
---
Vidi, Vici, Veni.

Submitted by Stavros on Thu, 26/07/2007 - 14:20.
GPL Content

This is great content and would be useful in teaching. Is this content released on the GPL, or please, can it be?

Submitted by Ian (not verified) on Fri, 10/08/2007 - 00:40.
Re: GPL

Well, since you ask nicely, this content is hereby released under the Creative Commons Attribution-Share Alike 3.0 License.
---
Vidi, Vici, Veni.

Submitted by Stavros on Fri, 10/08/2007 - 01:06.
Most retarded quide...

There are three categories of people (those who don't know python - non programmers and programmers, and those who do know python) and this article serves none of them:

1) Non-programmers will not learn python from this, but will get confused.
2) Programmers could care less about the guide as there are tons of them out there, some more some less concise but many simply more informative and useful, as most of this stuff is just too generic for them and not very useful.
3) Python programmers - duh, why would they need this?

Submitted by Anonymous (not verified) on Wed, 29/08/2007 - 19:28.
Re: Retarded

Well, at least you aren't going around the internet leaving useless comments in random blogs...
---
Vidi, Vici, Veni.

Submitted by Stavros on Wed, 29/08/2007 - 22:12.
I'm a programmer that had

I'm a programmer that had never read or written python. I needed to understand code written in python. This concise guide has been very helpful, and fun to read. Good job poromeno.

-ppp-

Submitted by Anonymous Coward (not verified) on Sun, 09/09/2007 - 19:53.
Re: Programmer

Why, thank you, sir :)
---
Vidi, Vici, Veni.

Submitted by Stavros on Sun, 09/09/2007 - 20:58.
category 1

I'm a nonprogrammer trying to learn python, but so far am only slightly confused. I found this tutorial helped a great deal. I'm trying to learn because Cory Doctorow says that everyone should write code at some point in their life.

Submitted by Keelis (not verified) on Fri, 28/11/2008 - 13:26.
integer methods

You can invoke methods on integers. It just requires disabiguing them from float using a space:

>>> 1 .__add__(2)
3

Submitted by Anonymous (not verified) on Tue, 20/11/2007 - 01:48.
My 2 cents

I just want to link to one of my favorite 'learn programming' type of articles:

teach yourself programming in 10 years

hope it helps someone. also, here are few more useful python links.

Submitted by Anonymous (not verified) on Fri, 23/11/2007 - 20:53.
Sweet Primer

Just wanted to let you know that I really appreciated your Python tutorial :)

Submitted by Joe Smith (not verified) on Mon, 07/01/2008 - 00:14.
documentation

Very good introduction to python.
I just like to suggest that maybe it can be worthwhile
to include a very short introduction to the dir() and help() functions, and to xxx.__doc__, so the user can start to read
the documentation in the python interpreter.

Submitted by guisf (not verified) on Wed, 23/01/2008 - 17:07.
Re: Documentation

Good idea, thanks!
---
Vidi, Vici, Veni.

Submitted by Stavros on Wed, 23/01/2008 - 19:06.
Instead of "The first item

Instead of "The first item in all array types is 0," I think you should have "The index of the first item in all array types is 0." It is clearer and causes less confusion.

Submitted by M (not verified) on Mon, 31/03/2008 - 03:51.
Re: Index

You are quite correct, thanks!
---
Vidi, Vici, Veni.

Submitted by Stavros on Mon, 31/03/2008 - 10:31.
'assign variable' -> 'bind name'

@author of the tutorial:

We do not assign a value to the variable in Python but we introduce a name referred to an object by name binding operation. See http://www.python.org/doc/current/ref/naming.html

This notation could greatly clarify discussions about passing function arguments and about immutable and modifiable objects in Python.

Submitted by Zart (not verified) on Wed, 02/04/2008 - 12:12.
Re: Binding

You are quite correct, I will fix this now.
---
Vidi, Vici, Veni.

Submitted by Stavros on Wed, 02/04/2008 - 14:03.
Advanced Tutorial

Great work! I admire your patience (your response to the idiot that said your tutorial is useless made me literally laugh out loud).

Can't wait for your (promised) Advanced Tutorial... (remember?)

Thanks for all the work you invested!

Submitted by Noam Nelke (not verified) on Thu, 17/04/2008 - 21:10.
Re: Advanced Tutorial

Thank you, I'm glad you liked it :)

I don't remember about the advanced tutorial, actually! When did I say it/what would you like to see in it?
---
Vidi, Vici, Veni.

Submitted by Stavros on Thu, 17/04/2008 - 23:54.
thanks so much!

Poromenos, this tutorial has been a godsend. Things are laid out so plainly, that I was able to come up to speed and write meaningful code very quickly.
Thank you so much, for distilling all this information down to what is most essential.

Submitted by Tom (not verified) on Wed, 21/05/2008 - 14:40.
great!

that's awesome! exactly what I was looking for.
thx

Submitted by meilione (not verified) on Tue, 27/05/2008 - 15:53.
What an awesome tutorial.

What an awesome tutorial. Despite the nitpicking from all the Python pros, as a non-Python programmer, I really enjoyed you 30,000 foot overview of the language, and am actually more excited about trying to learn, and maybe use it in the future. Despite the errors, or that you use Drupal instead of Plone (gasp) this was really helpful, and I learned something new.

Thanks.

Submitted by David Cloutman (not verified) on Tue, 05/08/2008 - 22:55.
Re: Tutorial

Well, in matters of precision, nitpicking matters :) I am glad you enjoyed the tutorial, thank you for your feedback.

Submitted by Stavros on Wed, 27/08/2008 - 16:20.
D'oh!

Rats. I just spent half a day learning elsewhere what I would've learned in...okay, 15...minutes here! Nice overview for us soon-to-be-formerly non-python programmers.

Submitted by murison (not verified) on Sun, 10/08/2008 - 04:41.
thank you

Didn't make it in 10 minutes but i did learn the basics, just what i was looking for. Thank you for writing this.

Submitted by Fabio Santos (not verified) on Wed, 13/08/2008 - 17:17.
Errata in Errata

It could be my browser. but the right side of your errata items / comments list is cut off and therefore useless. I can only read parts of sentences.

Submitted by Rand (not verified) on Fri, 05/09/2008 - 04:02.
Re: Errata

Damn, you're right. There's something wrong with the theme, I'll see if I can fix it, thank you.

Submitted by Stavros on Tue, 09/09/2008 - 08:33.
thanks

Thanks for the straight forward advice, this was an ideal starter to the language. Mind you, as a c programmer I'm still a little hazy on oo programming!

Submitted by Ads (not verified) on Sun, 07/09/2008 - 11:19.
thanks

Nice intro to Python. After moving from VB.net to ECMAscript languages it's good to get rid of those damn semi-colons and curly brackets again!

(I saw, I conquered, I didn't call)

Submitted by Anonymous (not verified) on Sat, 20/09/2008 - 04:15.
dynamically, implicitly typed

dynamically, implicitly typed (i.e. you don't have to declare variables)

it's true but this is not what defines dynamic typing : you do not need to declare types in staticly typed languages which have type inference (ML, Haskell)

- val x = 5;
val x = 5 : int
- val x = "five";
val x = "five" : string

dynamically typed languages are typed checked at run time

Submitted by Anonymous (not verified) on Fri, 28/11/2008 - 14:32.
I thought Python is easier to

I thought Python is easier to learn then Java and C++. I programm Java for 2 years and C++ more then 3, but i found Python very confusing and not easier then Java & C++. Maybe becouse i'm used to work with the other languages.

Submitted by Tomi (not verified) on Sat, 06/12/2008 - 20:14.
I forgot to mention, that

I forgot to mention, that this site is the best i found in the past two days. Thx for the tutorial,great work

Submitted by Tomi (not verified) on Sat, 06/12/2008 - 20:18.
thanx!!.. this was of great

thanx!!.. this was of great help to me as m working on python for the first time..

Submitted by Anonymous (not verified) on Wed, 17/12/2008 - 10:29.
Modulo missing

There’s a modulo missing in "Miscellaneous" part:
# Check how many items have this property.
>>> sum(1 for i in [3, 3, 4, 4, 3] if i 3)
Last line should be:
>>> sum(1 for i in [3, 3, 4, 4, 3] if i % 3)

Also, you don’t explain the "self" thing, which is a common pitfall for python learners.

Otherwise, it was a very nice tutorial :) Thanks!

Submitted by Aissen (not verified) on Sun, 25/01/2009 - 10:34.
Re: Errors

You are quite right, Textile was eating some of my symbols, everything should be fixed now. I will also write up an explanation of "self", thank you.

Submitted by Stavros on Sun, 25/01/2009 - 11:06.
Just to make it a little more

Just to make it a little more obvious you might consider changing

>>> sum(1 for i in [3, 3, 4, 4, 3] if i == 3)
3

to

>>> sum(1 for i in [3, 3, 4, 4, 3] if i == 4)
2

so that the 3 in the if statement doesn't match the resulting sum. That was confusing when I first saw it.

Submitted by RockySims (not verified) on Sat, 28/03/2009 - 00:45.
List comprehensions

Hi,
Nice tutorial, but it almost gave me a headache when I tried to understand the example:

# Check if an item has a specific property.
# "any" returns true if any item in the list is true.
>>> any(i % 3 for i in [3, 3, 4, 4, 3])
True

Finally, I understood that 0 was converted to False and the other values to True... is that right?

Submitted by nh2 (not verified) on Thu, 02/07/2009 - 13:17.
Re: List comprehensions

That is right, I am sorry for the omission, I will clarify it immediately. Thank you for the note.

Submitted by Stavros on Thu, 02/07/2009 - 15:39.
this site is in drupal . but

this site is in drupal . but the page is about the learning of python; good. i downloaded the plone cms and working . is anyone on the web use plone for their site.

Submitted by Anonymous (not verified) on Mon, 20/07/2009 - 09:25.
Thanks

Just a quick thanks. This was the first tutorial that I ran through. It's not bad at all.

Submitted by spiralofhope (not verified) on Thu, 20/08/2009 - 07:17.
Response to tutorial

Thanks a lot for this, it is really useful for newbies :>
Hope many of us will learn Python, and that it will stay in trend for a long time
Greetings once again maaan!!

Submitted by Anonymous (not verified) on Mon, 26/10/2009 - 20:41.
Thankyou

Thankyou. Just trying to get my teeth into Python and I have a feeling I understand some of the basics now.

Submitted by Adrian (not verified) on Mon, 16/11/2009 - 16:27.

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.

Ads