Skip to page content or Skip to Accesskey List.

Work

Main Page Content

Python Your Journey Starts Here

Rated 3.92 (Ratings: 2)

Want more?

 

Dody Gunawinata

Member info

User since: 23 Aug 1999

Articles written: 5

This is about learning Python. If you are looking for another article about how good Python is, you have come to the wrong place my friend. If you need only rhetoric and language bashing for and against Python, go to python.org. You will find plenty there. If this is the first time you have heard about Python, well, read this sample chapter from the excellent book Internet Programming with Python

Now, here's the deal. This article will show you enough to start programming in Python. If you have heard that Python is object oriented, well, I won't tell you how to make classes and stuff in this article yet. It would be in the coming soon section.

This is what you will learn here:

  • Declaring variables.
  • The ifs and elses.
  • The loops.
  • Creating and using your own functions.
  • Bits and pieces about python.

It's quite a lot, but this would get you started in no time. I don't like waiting for a week to find out how to use the if statement, I guess neither do you. These are basics and they should be explained in one go. I have deliberately decided not to cover every little peculiarities about Python in this article. That kind of material is more suitable for a book, or at least, not for an introductory article like this.

Here's a little secret for you, there is a complete and exhaustive 'free' book on Python available electronically on the Net. Its title is Quick Python, just released on paper. However, you can get the draft version for free. It's available here. If you like it, buy it, because sometimes it's a lot better to read on paper than on screen. And don't forget to give the author a pat on the back for the gutsy move of allowing potential readers to download it for free. You might as well forget that this article ever existed and learn by reading this book instead. But I believe you can learn the Python basic faster in this article than the book because, like many other technical books, there are lots of words 'wasted' in the book before it actually starts to teach you something about Python. Speaking of self promotion. Ok, warm up your computer, and let's start coding.

Using your Python interpreter.

  1. Interactive mode
    This is when you invoke the interpreter by just typing the command "python". Of course you would not want to spend a lot of your time programming in this session. Mainly because you can't save what you have written in the interactive mode and well, it's pain in the ass to write a lot of code in it. On the other hand, the interactive session is great for learning the features of the languages and testing library calls. Guido, the father of Python, has written an introductory tutorial for Python using this method. Get it at http://python.org.
  2. Type source code in text file, save as file with extension .py, type command "python sourcecode.py", and see the result mode
    Once you start to write more and more Python code, this is the only reasonable way of doing it.

Variables

  • No type declaration.
  • You can declare it anywhere.
  • Variable does not remember its type.
  • You assign value to a variable using '=' sign.

It's important to note that Python does not use any special symbol for grouping statement. So there is no { } or begin end marker. It uses TAB to group statement (in other words, indentation). Wierd but don't worry, over the time you'll appreciate this feature. It forces you to 'pretty print' your source code from the start, which is a Good Thing™. You will see this rule in action in the next topic.

There is no need to declare the type of your variable. And everything that starts with # is considered as a comment. It's a single line comment.

#Declare the variables

stringVariable = "test"

integerVariable = 24

floatingVariable = 34.3

Use the print keyword to print the variable content to the screen. Yes, it's a language feature, not just a function.

Notice that there is no special symbol or stuff like that in order to print the variable content. Notice the comma used to 'chain' variables in the single print statement.

print stringVariable

print integerVariable

print floatingVariable

You can mix displaying different type of variable in a single print statement. Notice that there is no extra space needed in the string because print would add it automatically if two different type are displayed in the same line. Smart eh?

print 'My first', stringVariable, "of

Python script", integerVariable,

floatingVariable

Using print alone will give you a new line.

print

You can also do mathematical expression in the print statement.

print integerVariable, ' * 2 = ',

integerVariable * 2

As you might have noticed from the previous example, every print statement adds a new line. Use a comma (',') to prevent print adding a line break.

print "this sentence without ",

print "line breaks"

Use the '=' to assign value from one variable to another.

anotherString = stringVariable

Variable does not 'remember' its previous value's (implicit) type. So you can use one variable over and over again with different type of value. Use it with care.

stringVariable = floatingVariable

You can use '' (single quotes) or "" (double quotes) for string literal. To display '' (single quote) in the string, enclose the string within double quotes mark. I prefer double quotes just for its consistency. I use single quotes in the previous examples just to let you know it can be done. After the following example, I will stay true to my double quotes.

print 'Single quote '

print " Double quote "

ifs and elses

if_stmt: "if" expression ":" suite

"elif" expression ":" suite)*

["else" ":" suite]

It supports the usual band of Boolean operators and some. They are 'and, or, not, ==, !=, <> (the same as !=, inequality), >, <, >=, <=' and some more. Let me again emphasise the fact that Python uses TAB indentation for grouping statements. So if a TAB in your editor adds four spaces to the right, entering four spaces and making a statement aligned with the rest of the group statements will still result in error. It's the TAB that counts.

x = 30

if x > 20 :

print "x is less than 20

elif x == 20:

print "x is equal 20"

print "and not less than 20"

else:

print "x is definitely larger than 20"

if x > 40 :

print "like this one, larger than 40"

else :

print "still larger then 20, but less or equal 40"

While loops

while_stmt: "while" expression ":" suite

["else" ":" suite]

Let's talk about some keywords exist just for the loop.

  • break as in C, Java or Object Pascal, breaks out from the current loop.
  • continue continues with the next iteration of the loop.
  • else clause in below example is optional. It only gets executed when the loop terminates normally through the exhaustion of the list (for loop) or when the condition become false (while loop), but not when the loop is terminated by break statement. So the following code will print 'Get to the end' after the numbers get printed.

#Loop 10 times<br> x = 0

while x < 10:

print x

x = x + 1

else:

print "Get to the end"

And you know now that the string in the else clause on the following function will not get printed. You might as well remove the else clause. And let me remind you again, Python uses TAB for statement grouping. Notice as well that the else clause are in the same indentation as the while keyword.

#NOTICE that else: is at the same indentation

#as the while:

#Loop only 2 times

x = 0

while x < 10:

if x >= 2:

break

print x

x = x + 1

else:

print "This ain't getting printed"

For loops

for_stmt: "for" target_list "in" expression_list ":" suite

["else" ":" suite]

There is no concept of loop incrementing a variable from low to high or vice versa in Python. The for loop is designed to iterate on a list. You can define a list and let the for loop iterate over it, or better yet, call range() function to generate the list for you automatically so you can just use it. Just remember that the loop iterates for the total number of element in the list. [100,200] is a list. A loop would iterates twice on this list, just the same as [1,2]. [100,1,200] would result in 3 loops. See that there is no concept of low and high value. As you remember, the for loop also come with the optional else clause. It behaves the same with its while loop counterpart. Let's the loop iterates on your list.

a = ['a','b','c']

for x in a:

print x #this prints a, b and c

And check out the list the cool function range() generates for you.

#This is the result of a range function call

print range(3) #prints [0,1,2]

print range(-3,4) #prints [-3,-2,-1,0,1,2,3]

And use it for your loop pleasure.

#the simple for loop..loop 10 times

for x in range(10):

print x

#see the flexibility of range function here.

#This loops for 6 times.

for x in range(4,10):

print x

The good old function

funcdef: "def" funcname "(" [parameter_list] ")" ":" suite

parameter_list: (defparameter ",")* ("*" identifier [, "**" identifier] |

"**" identifier |

defparameter [","])

defparameter: parameter ["=" expression]

sublist: parameter ("," parameter)* [","]

parameter: identifier | "(" sublist ")"

funcname: identifier

Let me remind you again that Python uses TAB to group statements. So like other construct in Python, a function is defined by a def keyword, and statements belong to the function are just indented together.

This is the simplest form of function you can define in Python. Void function without any parameter. Notice the 'documentation string'. It's not required, but it's really a good habit to explain what your function do, and some documentation tools uses this documentation string to document your function automatically. Just like Java with its Javadoc.

#'void' function without any parameter

def voidFunction ():

"This is known as 'documentation string'"

print "voidFunction(): This function returns nothing"

#This is how you call parameterless function

voidFunction()

I only tell you half the truth when I say you can create void function in Python. Your 'void' function actually returns a value, albeit a boring one, None. None in other language is known as null, Null, or Nul in other languages. Notice the capital N.

#'void' function actually returns 'None' value

print voidFunction()

Now, let's create a function that actually returns a real value. As you see, there is no difference between the declaration of the next function with it's 'void' counterparts. The only thing that separates them is that below functions has return statement with value. So the value returned from the function actually depends on what you put on the return statement.

#This function actually returns something

def returnFunction():

"""However, this style with three double quotes

is recommended, as you see, multiple line

span"""

i = 'returnFunction(): This string would be returned'

return i

#see the result

print returnFunction()

The return keyword actually can be used for another purpose, which is it enables you to exit the function immediately. It's useful for some situation. And you don't need to specify a value for the return keyword either. If you don't give a value, it returns None.

def returnNone():

"""Documentation is not required, but recommended so

some external tools can use it to document your function.

Just like JavaDoc"""

return

print "returnNone(): This doesn't get printed at all"

returnNone() #This function does nothing

print returnNone() #This would print 'None'

And of course function in Python can accept arguments. Well, as you might have guessed, no type declaration needed either.

Notice the single line function. It's quite common to see Python source code with this kind of style for single statement function. I prefer to indent the single statement because it enables me to read faster.

#Function with parameter, no type is needed. Notice the

#single line function

def parameterFunction (First, Second): print First, ' ', Second

#Calling it

parameterFunction ("String arguments", 40)

parameterFunction (58.43, "it's float")

As you see above, Python doesn't enforce the type at all. It's up to the programmer to be careful with passing arguments. Python does raise an error if the type is incompatible with the operation in the function, which is not the case with the above function.

This is another trick in Python for function. Default parameter.

def defaultFunction (MyName, Age = 21, MoneyLeft = 30.25) :

""""""

print "My name is", MyName

print "I am", Age, "years old "

print "I have only", MoneyLeft, "in my pocket"

#Five wicked ways to call the function

print

defaultFunction ("John")

print

defaultFunction ("John",30)

print

defaultFunction ("John",30, 300.00)

print

defaultFunction ("John", MoneyLeft = 1000.00);

cpodeprint

defaultFunction (Age = 90, MyName = "John")

Last but not the least, you can assign your function to another variable. Just like a function pointer (using C terms). Notice that you don't use the () argument mark, because doing so means that you are assigning value from the function instead.

anotherDefaultFunction = defaultFunction

anotherDefaultFunction ("John")

Well, that's all for this time. Next time, I will cover the ways of data structure in Python. There are quite many of them, and they are quite cool. I would add snippets about classes here and there as well. And we'll be thinking about the Zope way. Until next time, enjoy your Python...

Oh, a little note. Drop me a line and tell me what you think about this article. I also appreciate any suggestions or corrections (grammatical or technical).

The access keys for this page are: ALT (Control on a Mac) plus:

evolt.org Evolt.org is an all-volunteer resource for web developers made up of a discussion list, a browser archive, and member-submitted articles. This article is the property of its author, please do not redistribute or use elsewhere without checking with the author.