Revision of Learn Python in 10 minutes from Tue, 14/10/2008 - 21:17

Shameless plug: If you want a free online financial management app, you could do me a favor and visit www.moneygement.com, see if it’s to your liking. Thanks.

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, so it will just show you some basic concepts to start you off. Obviously, if you want to really learn a language you need to program in it for a while. I will 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. Also, pay attention because, due to the terseness of this tutorial, some things will be introduced directly in code and only briefly commented on.

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).

Getting help

Help in Python is always available right in the interpreter. If you want to know how an object works, all you have to do is call help(<object>)! Also useful are dir(), which shows you all the object’s methods, and <object>.doc, which shows you its documentation string:

>>> help(5)
Help on int object:
(etc etc)

>>> dir(5)
['__abs__', '__add__', ...]

>>> abs.__doc__
'abs(number) -> number\n\nReturn the absolute value of the argument.'

Syntax

Python has no mandatory statement termination characters and blocks are specified by indentation. Indent to begin a block, dedent to end one. Statements that expect an indentation level end in a colon (:). Comments start with the pound (#) sign and are single-line, multi-line strings are used for multi-line comments. Values are assigned (in fact, objects are bound to names) with the equals sign (”=”), and equality testing is done using two equals signs (”==”). You can increment/decrement values using the += and -= operators respectively by the right-hand amount. This works on many datatypes, strings included. You can also use multiple variables on one line. For example:

>>> myvar = 3
>>> myvar += 2
>>> myvar
5
>>> myvar -= 1
>>> myvar
4
"""This is a multiline comment.
The following lines concatenate the two strings."
""
>>> mystring = "Hello"
>>> mystring += " world."
>>> print mystring
Hello world.
# This swaps the variables in one line(!).
# It doesn't violate strong typing because values aren't
# actually being assigned, but new objects are bound to
# the old names.
>>> myvar, mystring = mystring, myvar

Data types

The data structures available in python are lists, tuples and dictionaries. Sets are available in the sets library (but are built-in in Python 2.5 and later). Lists are like one-dimensional arrays (but you can also have lists of other lists), dictionaries are associative arrays (a.k.a. hash tables) and tuples are immutable one-dimensional arrays (Python “arrays” can be of any type, so you can mix e.g. integers, strings, etc in lists/dictionaries/tuples). The index of 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:

>>> sample = [1, ["another", "list"], ("a", "tuple")]
>>> mylist = ["List item 1", 2, 3.14]
>>> mylist[0] = "List item 1 again"
>>> mylist[-1] = 3.14
>>> mydict = {"Key 1": "Value 1", 2: 3, "pi": 3.14}
>>> mydict["pi"] = 3.15
>>> mytuple = (1, 2, 3)
>>> myfunction = len
>>> print myfunction(mylist)
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. Negative indexes count from the last item backwards (thus -1 is the last item) like so:

>>> mylist = ["List item 1", 2, 3.14]
>>> print mylist[:]
['List item 1', 2, 3.1400000000000001]
>>> print mylist[0:2]
['List item 1', 2]
>>> print mylist[-3:-1]
['List item 1', 2]
>>> print mylist[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" % (myclass.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:

rangelist = range(10)
>>> print rangelist
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
for number in rangelist:
    # Check if number is one of
    # the numbers in the tuple.
    if number in (3, 4, 7, 9):
        # "Break" terminates a for without
        # executing the "else" clause.
        break
    else:
        # "Continue" starts the next iteration
        # of the loop. It's rather useless here,
        # as it's the last statement of the loop.
        continue
else:
    # The "else" clause is optional and is
    # executed only if the loop didn't "break".
    pass # Do nothing

if rangelist[1]  2:
    print "The second item (lists are 0-based) is 2"
elif rangelist<sup class="footnote"><a href="#fn13060439204c83cd9a45ef8">1</a></sup>  3:
    print "The second item (lists are 0-based) is 3"
else:
    print "Dunno"

while rangelist[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. Parameters are passed by reference, but immutable types (tuples, ints, strings, etc) cannot be changed. This is because only the memory location of the item is passed, and binding another object to a variable discards the old one, so immutable types are replaced. For example:

# Same as def f(x): return x + 1
functionvar = lambda x: x + 1
>>> print functionvar(1)
2

# an_int and a_string are optional, they have default values
# if one is not passed (2 and "A default string", respectively).
def passing_example(a_list, an_int=2, a_string="A default string"):
    a_list.append("A new item")
    an_int = 4
    return a_list, an_int, a_string

>>> my_list = [1, 2, 3]
>>> my_int = 10
>>> print passing_example(my_list, my_int)
([1, 2, 3, 'A new item'], 4, "A default string")
>>> my_list
[1, 2, 3, 'A new item']
>>> my_int
10

Classes

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

class MyClass:
    common = 10
    def __init__(self):
        self.myvariable = 3
    def myfunction(self, arg1, arg2):
        return self.myvariable

    # This is the class instantiation
>>> classinstance = MyClass()
>>> classinstance.myfunction(1, 2)
3
# This variable is shared by all classes.
>>> classinstance2 = MyClass()
>>> classinstance.common
10
>>> classinstance2.common
10
# Note how we use the class name
# instead of the instance.
>>> MyClass.common = 30
>>> classinstance.common
30
>>> classinstance2.common
30
# This will not update the variable on the class,
# instead it will bind a new object to the old
# variable name.
>>> classinstance.common = 10
>>> classinstance.common
10
>>> classinstance2.common
30
>>> MyClass.common = 50
# This has not changed, because "common" is
# now an instance variable.
>>> classinstance.common
10
>>> classinstance2.common
50

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

>>> classinstance = OtherClass("hello")
hello
>>> classinstance.myfunction(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 classinstance.
>>> classinstance.test = 10
>>> classinstance.test
10

Exceptions

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

def some_function():
    try:
        # Division by zero raises an exception
        10 / 0
    except ZeroDivisionError:
        print "Oops, invalid."
    else:
        # Exception didn't occur, we're good.
        pass
    finally:
        # This is executed after the code block is run
        # and all exceptions have been handled, even
        # if a new exception is raised while handling.
        print "We're done with that."

>>> some_function()
Oops, invalid.
We're done with that.

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

randomint = random.randint(1, 100)
>>> print randomint
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
mylist = ["This", "is", 4, 13327]
# Open the file C:\binary.dat for writing. The letter r before the
# filename string is used to prevent backslash escaping.
myfile = file(r"C:\binary.dat", "w")
pickle.dump(mylist, myfile)
myfile.close()

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

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

# Open the file for reading.
myfile = file(r"C:\binary.dat")
loadedlist = pickle.load(myfile)
myfile.close()
>>> print loadedlist
['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]
# 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
# Check how many items have this property.
>>> sum(1 for i in [3, 3, 4, 4, 3] if i  3)
3
>>> del lst1<sup class="footnote"><a href="#fn2910544744c83cd9a6f708">0</a></sup>
>>> print lst1
[2, 3]
>>> del lst1

==

  • Global variables are declared outside of functions and can be read without any special declarations, but if you want to write to them you must declare them at the beginning of the function with the “global” keyword, otherwise Python will bind that object to a new local variable (be careful of that, it’s a small catch that can get you if you don’t know it). For example:

number = 5

def myfunc():
    # This will print 5.
    print number

def anotherfunc():
    # This raises an exception because the variable has not
    # been bound before printing. Python knows that it an
    # object will be bound to it later and creates a new, local
    # object instead of accessing the global one.
    print number
    number = 3

def yetanotherfunc():
    global number
    # This will correctly change the global.
    number = 3

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 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 or if there is anything else you would like to see (classes, error handling, anything).
Creative Commons License
This work is licensed under a Creative Commons Attribution-Share Alike 3.0 License.

Tags:
your signature...

it's vini vidi vinci, i saw, i came, i won.

Submitted by eyko (not verified) on Fri, 13/01/2006 - 04:10.
Re: Sig

Think about it :P
---
Vidi, Vici, Veni.

Submitted by Stavros on Fri, 13/01/2006 - 08:57.
excellant free Python Interpretor

Hey all,

I have used Python for the past year and 1/2 here at my employment. While there are many free versions out there; many lack all the libraries and you have to hunt for the library to install. Thus is the case with python that comes pre-installed in many Linux OS's and freebsd. I have used the Enthought Edition of Python. It includes all Libraries, a nice color editor, and a run-time environment. It is free version and appears to only be supported for Window's OS's; but I have migrated some of my routines to Linux without any problems (provided all the libraries are installed on the Linux machine). Check it out for youself at:

http://enthought.com/

After all it is free - so it does no harm in trying it. I like it a lot and have is running several scripts to move data around on a Windows 2000 server. Plus, I have some pet projects on my PC; and will be building some church administration software.

Submitted by Rev. Scott Hervieux (not verified) on Fri, 13/01/2006 - 14:55.
His sig.

I suspect he knows that.

I think he's making a lewd funny, for those (like me) who are paying close enough attention. ;)

I, for one, smiled when I saw it.

("I saw, I conquered, I came.")

Submitted by reverted (not verified) on Sun, 11/01/2009 - 19:44.
no... it's "veni vedi vici"

no... it's "veni vedi vici"

Submitted by Anonymous (not verified) on Mon, 09/03/2009 - 19:55.
Veni, vidi, vici

It actually means I came, I saw, I conquered.
http://en.wikipedia.org/wiki/Veni,_vidi,_vici

Submitted by Anonymous (not verified) on Tue, 14/04/2009 - 17:36.
multidimentional lists

Scipy has no "multidimentional lists". Scipy has no lists, scipy introduces multidimentional arrays in Python (and a lot of array-related tools).

Submitted by Nil (not verified) on Thu, 10/08/2006 - 00:53.
Re: Multidimensional lists.

If we were talking about anything else, I'd make fun of you for being too pedantic, but since we're discussing programming, I can only admit that you're right :)
---
Vidi, Vici, Veni.

Submitted by Stavros on Thu, 10/08/2006 - 01:05.
Multiline comments

You can do multiline comments with the triple quoting:

''' This is a multiline comment.
You can put it anywhere in your code.
Yep, using any number of lines you wish.
'''

that's how most of the documentation is done in the sources, I don't know how you didn't spot it ;)

Submitted by LKRaider (not verified) on Sun, 15/07/2007 - 06:58.
Re: Multiline comments

I actually didn't know you can put them anywhere, I thought you could only use them as docstrings as freeform. I will implement them now, thank you for the suggestion :)
---
Vidi, Vici, Veni.

Submitted by Stavros on Sun, 15/07/2007 - 10:21.
WTFFFF

why the fxxx people learn to talk to computer in the world? learn another human language before you die.

Submitted by Anonymous (not verified) on Fri, 13/11/2009 - 23:01.
Numbers have methods ..

"I.e. the number 4 is not an object, it has not class, or methods."

Well, it has these:

>>> dir(4)
['__abs__', '__add__', '__and__', '__class__', '__cmp__', ....
'__truediv__', '__xor__']

>>> getattr(4, '__or__')
<method-wrapper object at 0xb7be954c>

Submitted by Mr. Anonymous Picky (not verified) on Sat, 18/02/2006 - 17:23.
Mr Anonymous Picky is right!

Since Python 2.2, (nearly) everything (let's say everything) is object based. Especially numbers and strings which were previously abnormalities.
For example on Python 2.1, you had:

>>> dir(4)
[]

But starting with Python 2.2+, you have now:

>>> dir(4)
['__abs__', '__add__', '__and__', '__class__', '__cmp__', '__coerce__', '__delattr__', '__div__', '__divmod__', '__doc__', '__float__', '__floordiv__', '__getattribute__', '__getnewargs__', '__hash__', '__hex__', '__init__', '__int__', '__invert__', '__long__', '__lshift__', '__mod__', '__mul__', '__neg__', '__new__','__nonzero__', '__oct__', '__or__', '__pos__', '__pow__', '__radd__', '__rand__', '__rdiv__', '__rdivmod__', '__reduce__', '__reduce_ex__', '__repr__', '__rfloordiv__', '__rlshift__', '__rmod__', '__rmul__', '__ror__', '__rpow__', '__rrshift__', '__rshift__', '__rsub__', '__rtruediv__', '__rxor__', '__setattr__', '__str__', '__sub__', '__truediv__', '__xor__']

It's the same for strings (strings HAD methods even before v2.2 but they were cheated).

Submitted by Lior Gradstein (not verified) on Wed, 08/03/2006 - 13:55.
Learnt a lot about

Learnt a lot about Python-thought it was more than 10 minutes. Also yes it seems to support Ojects; it is Functional; and it is Procedural.finis.

Submitted by ha_python (not verified) on Sat, 04/10/2008 - 10:25.
The "Exceptions" section

The "Exceptions" section seems to have a formatting error, I guess 'try-except' should be highlighted and the code around it should do that.

Very nice tutorial by the way.

Submitted by mariuss (not verified) on Fri, 13/01/2006 - 18:00.
Re: Error

Thanks, Textile was acting up :)
---
Vidi, Vici, Veni.

Submitted by Stavros on Fri, 13/01/2006 - 20:31.
I/O

Hi, first of all, great article. I think it would be a nice addition to it if you would include one sample of using the "vast array" of libraries that Python provides. And in my opinion, the best example would be basic textfile Input/Output.

Cheers, busfahrer

Submitted by busfahrer (not verified) on Sat, 14/01/2006 - 15:05.
Re: I/O

I have added importing, serializing and I/O, although I think this is only barely in the scope of the tutorial, since it (serializing) is not a core function. Still, it is an example of external libraries, I/O (which is a core function) and importing (which was missing from the previous version).

Thanks for the suggestion :).
---
Vidi, Vici, Veni.

Submitted by Stavros on Sat, 14/01/2006 - 15:58.
Re: I/O

The I/O and (de)serializing examples are interleaved, i.e., the call to pickle.dump is followed by calls to flFile.write/read, then by a call to pickle.load. The latter will obviously fail to load the serialized data, because it was overwritten by flFile.write.

Submitted by Roger (not verified) on Thu, 02/02/2006 - 21:01.
Re: I/O

I think you made a small mistake, the first file is file.dat and the second is file.txt, so they wouldn't be overwritten. I'll change the filenames though.
---
Vidi, Vici, Veni.

Submitted by Stavros on Fri, 03/02/2006 - 14:50.
leading vs trailing

Private variables and methods can be declared by adding at least two trailing underscores and at most one leading one (e.g. "__spam").

Well, not quite...

Submitted by Anonymous (not verified) on Mon, 16/01/2006 - 18:36.
Re: Leading

Yes :/
---
Vidi, Vici, Veni.

Submitted by Stavros on Tue, 17/01/2006 - 02:16.
Veni Vidi Vici

You are both wrong, its: Veni Vidi Vici

Submitted by Anonymous (not verified) on Sat, 11/02/2006 - 18:14.
Re: Sig

A misquotation of "Veni, vidi, vici", it was chosen for its strong sexual overtones, meaning "I saw, I conquered, I came".
---
Vidi, Vici, Veni.

Submitted by Stavros on Sat, 11/03/2006 - 11:56.
Minor typo

Minor typo:

"equality testing **it** done using two equals signs"

Submitted by Anonymous Mathematician (not verified) on Sun, 12/02/2006 - 06:01.
Re: Typo

Duly changed, thank you sir.
---
Vidi, Vici, Veni.

Submitted by Stavros on Sun, 12/02/2006 - 13:37.
lists are not arrays

Lists and arrays are fundamentally different data structures. Lists are objects chained by references, arrays are contigous blocks of memory. Python does not have arrays at all, perhaps except for tuples which are somewhat like immutable arrays. Python Lists are certainly not "one-dimensional arrays". However, download the excellent NumPy package and get real arrays in python.

Submitted by Anonymous (not verified) on Wed, 08/03/2006 - 00:30.
Re: Lists

What you say is correct, but I think that's a bit more on the technical side and beyond the scope of the tutorial. However, since it exists in the comments, it is an excellent addition for someone who wants to read a bit more about it.
---
Vidi, Vici, Veni.

Submitted by Stavros on Wed, 08/03/2006 - 09:49.
The funny part is that

The funny part is that Python lists are implemented using arrays and not using chained structures.
In a sense, Python lists are arrays. If you want chained lists, use nested arrays ;-)

emptylist = [None,None]
l = [1,[2,[3,[None,None]]]]

def Append(l,val):
while l[1]:
l = l[1]
l[0] = val
l[1] = [None,None]

Append(l,4)
print l

Submitted by Anonymous (not verified) on Sat, 11/03/2006 - 16:30.
Well....

I would like to learn Python but i don't understand all these words...Does anyone no of any other tutorial for a child at 14 years old?

Submitted by Milky (not verified) on Sat, 08/04/2006 - 20:52.
Re: Well...

Unfortunately, this tutorial is aimed at people with previous programming knowledge. You might want to find a tutorial for programming in general before you read this.
---
Vidi, Vici, Veni.

Submitted by Stavros on Sat, 08/04/2006 - 21:04.
well...

a good one i have found to start with is at
http://www.freenetpages.co.uk/hp/alan.gauld/

Submitted by William (not verified) on Sun, 09/07/2006 - 22:21.
Good Beginner Python Tut

First off, I have to say that drupal is cool, as my site www.undug.net is on drupal, but i also have to say that yours doesn't look good, because its the default theme. Anyhow, all that aside, the good python tutorial, is at Jinx.com/forum/ in the Tutorials/faq message board... and i've learned from it and i'm only 14 so yeah. have fun.

Submitted by Robbins (not verified) on Fri, 01/09/2006 - 18:27.
Excellent

I know programming languages like C, C++, java, and other scripting languages like shell scripts, perl, tcl. This is an excellent tutorial for someone like me to get started with python.

Thank you so much!!

Submitted by Anonymous (not verified) on Sun, 09/04/2006 - 04:19.
Re: Excellent

I'm glad you liked it :)
---
Vidi, Vici, Veni.

Submitted by Stavros on Sun, 09/04/2006 - 08:26.
Thanks for the tutorial

Thanks for the excellent tutorial.
Though it did not make me a pro, its enough to get me very interested in Python.
You have introduced me to a lot of new concepts which make Python worth learning.

Regards,
Swap0

Submitted by Swap0 (not verified) on Sun, 30/07/2006 - 09:19.
Lists & Differing Types

Don't arrays only hold elements of the same type? Wikipedia claims this. Yet you described Python lists as "one-dimensional arrays" even though they can have elements of multiple types. I think this could be very confusing to people who are only familiar with arrays holding a single type.

Submitted by HeroreV (not verified) on Wed, 30/08/2006 - 01:24.
Re: Lists

This is true. I will change it anon.
---
Vidi, Vici, Veni.

Submitted by Stavros on Wed, 30/08/2006 - 09:16.
Nice article

I'm an experienced programmer but new to Python. I found the tutorial great - very succinct and gave me enough to write a few programs of my own almost immediately. It took a little more than 10 minutes though. ;)

There are endless additions that could be made, but why not write an additional "advanced" tutorial to take people to the next level? That might include simple regular expresssions, or demonstrating simple SQLite data access. Anyway, great tutorial and thanks a lot!

Submitted by Anonymous (not verified) on Sun, 17/09/2006 - 21:39.
Re: Nice article

That is actually a very good idea. I will get on it when I have some time, thanks :)
---
Vidi, Vici, Veni.

Submitted by Stavros on Mon, 18/09/2006 - 12:51.
Correction...

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).

If we remove the parentheses this reads:
Python is strongly typed, dynamically, implicitly typed, case sensitive and object-oriented.

I think a better way of wording this would be:
Python is implicitly and strongly typed, dynamic, case sensitive and object-oriented.

Great article I know perl and C and C++ and this got me started on python right away
oh \\'#?

Submitted by The Ranman (not verified) on Tue, 27/03/2007 - 09:12.
Re: Correction...

Hello and thank you for your corrections. I tried to implement it but it breaks the grouping of the parentheses (implicitly typed and dynamic are kind of in the same ballpark). Also, the "dynamic" in my sentence refers to having dynamic typing, not being a dynamic language (which Python is both).

I look forward to more of your suggestions :)
---
Vidi, Vici, Veni.

Submitted by Stavros on Wed, 28/03/2007 - 10:45.
Kudos

Excellent tutorial for someone that has enough background in programming and needs to pick up the basics quickly. A little more details in the OO stuff would be appreciated.
I admire the quality of your work and, even more so, your courage, patience and positive response to all the comments, regardless of the source or content.

Submitted by LazyHack (not verified) on Tue, 17/04/2007 - 18:57.
Re: Kudos

Thank you for your praise :) What kind of details would you like to see in the OO part? Python is rather straightforward with that, so I didn't know what else to write, but suggestions are always welcome!
---
Vidi, Vici, Veni.

Submitted by Stavros on Tue, 17/04/2007 - 19:04.
Pep-8 Style

As a Python enthusiast, I really like your tutorial and the effort you put into spreading the word.

It would be nice for your tutorial to follow the Python style guide:
http://www.python.org/dev/peps/pep-0008/

- Naming convention for functions and instance variables is lowercase with words separated by underscores.
- It is not common to prefix functions to indicate grouping (or something Hungarianesk)
- Functions can be documented, using with a `docstring`, using """triple double quotes""" (see http://www.python.org/dev/peps/pep-0257/)

Given these guidelines,

def fnMyFunction():
    # This will print 5.
    print intNumber

def fnOther():
    # This raises an exception because the variable has not
    # been assigned to before printing. Python knows that a
    # value will be assigned to it later and creates a new, local
    # intNumber instead of accessing the global one.
    print intNumber
    intNumber = 3

would be written as:

def my_function():
    """print global `number`, 5 in this example """
    print number

def other():
    """This raises an exception because `number` has not
    been assigned to before printing. Python knows that a
    value will be assigned to it later and creates a new, local
    `number` instead of accessing the global one.
    """
    print number
    number = 3

Submitted by Nederhoed (not verified) on Thu, 12/07/2007 - 19:31.
global variables in functions

The comment in one of the last functions of the tutorial could be improved upon to make it more readable. I've pasted a before and after here:

--
# This raises an exception because the variable has not
# been assigned to before printing. Python knows that it a
# value will be assigned to it later and creates a new, local
# intNumber instead of accessing the global one.

--

# This raises an exception because the variable has not
# been assigned to before printing. Python knows that a
# value is assigned in this function block, and thus
# works on a local instantiation instead of any global one.

Submitted by Anonymous (not verified) on Thu, 12/07/2007 - 21:12.
Please get rid of the hungarian notation...

It's so unnecessary, adds bloat, and makes the code look like something out of Visual Basic. Not only that, but you're doing "systems hungarian", which is a discredited approach to start with. Python already knows what types things are, so the type prefixes are doubly unnecessary.

Submitted by Phillip J. Eby (not verified) on Fri, 13/07/2007 - 15:35.
Re: Hungarian notation

Changed, as per your wishes.
---
Vidi, Vici, Veni.

Submitted by Stavros on Fri, 13/07/2007 - 16:16.
Show how returned tuple works

Although it's relatively clear based on your description, it would be even better if your code example:

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

was followed by the print results of ret1, ret2, and ret3.

I'm guessing it would be

Named argument 100 Argument 1

This is especially important since returning a tuple is unique to python.

Submitted by Tim (not verified) on Fri, 13/07/2007 - 16:03.
Re: Returned

Done and done.
---
Vidi, Vici, Veni.

Submitted by Stavros on Fri, 13/07/2007 - 16:15.

Comment viewing options

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

Ads