Main Page Content
Python Your Journey Starts Here
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 PythonNow, 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.
Using your Python interpreter.
- 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. - 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.
#Declare the variablesstringVariable = "test"integerVariable = 24floatingVariable = 34.3Use 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 stringVariableprint integerVariableprint floatingVariableYou 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, "ofPython script", integerVariable,floatingVariableUsing print alone will give you a new line.
print
You can also do mathematical expression in the print statement.print integerVariable, ' * 2 = ',integerVariable * 2As 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 = 30if x > 20 :
print "x is less than 20elif 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 = 0while x < 10: print x x = x + 1else: 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 timesx = 0
while x < 10:
if x >= 2: break print x x = x + 1else: 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 cAnd check out the list the cool function range() generates for you.
#This is the result of a range function callprint 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 timesfor 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] ")" ":" suiteLet 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.parameter_list: (defparameter ",")* ("*" identifier [, "**" identifier] |
"**" identifier | defparameter [","])defparameter: parameter ["=" expression]
sublist: parameter ("," parameter)* [","]
parameter: identifier | "(" sublist ")"
funcname: identifier
#'void' function without any parameterdef voidFunction (): "This is known as 'documentation string'" print "voidFunction(): This function returns nothing"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.#This is how you call parameterless function
voidFunction()
#'void' function actually returns 'None' valueprint 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 somethingdef returnFunction():"""However, this style with three double quotesis recommended, as you see, multiple linespan""" i = 'returnFunction(): This string would be returned' return i
#see the resultprint 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 sosome 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 nothingprint 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 functiondef parameterFunction (First, Second): print First, ' ', SecondAs 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.#Calling it
parameterFunction ("String arguments", 40)parameterFunction (58.43, "it's float")
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"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.#Five wicked ways to call the function
printdefaultFunction ("John")printdefaultFunction ("John",30)printdefaultFunction ("John",30, 300.00)printdefaultFunction ("John", MoneyLeft = 1000.00);cpodeprintdefaultFunction (Age = 90, MyName = "John")
anotherDefaultFunction = defaultFunctionanotherDefaultFunction ("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).