Introduction To Python

11 June, 2010
-Lionel Tan Yoke Liang-

_____________________________________________________________

Objective

Note:-

Please take note that, this tutorial is not meant to prepare you to ownage, neither is it meant to make you a python guru after completing it.
This tutorial only serves as a platform to introduce how to program in python, so you we can program using this language in the shortest time.
As the saying goes, Learning Is a Lifelong Process, and if you are interested in getting to know more about this language, the internet is the best free place to go.
Do check out the last part of this page for a list of websites which I personally think is very useful.


[top]





Table Of Content:-

  1. Things That You Need To Know Before Starting[link]
    1. Python Blocks
    2. Running Python
      1. System Call Mode
      2. Interactive Mode
    3. Help

  2. Data Types and Data Structures[link]
    1. Variables
      1. numbers
      2. string
    2. Collections
      1. list
      2. dict
      3. tuple

  3. Conditional Loops[link]
    1. Loops
      1. if ... elif ... else
      2. for
      3. while
    2. Control
      1. break
      2. continue
      3. else
    3. List Comprehension

  4. Functions[link]
    1. Defining
    2. Calling a Function
    3. Passing In Data
    4. Returning Data

  5. Dealing With Files[link]
    1. Reading From Files
    2. Writing To File

  6. Classes And Objects[link]
    1. Terminology
    2. Creating A Class
    3. Constructor
    4. Methods

  7. Useful Links[link]

  8. Google Python Class (Video)[link]



[top]

  1. Things That You Need To Know Before Starting
    1. Python Blocks
    2. It's very important to know that python uses a very unique way of representing it's block of codes.
      While most of the languages uses the curley braces ...
      #!/apps/perl/bin/perl
      if (1)
      {
      	print "Hello, World";
      	return(0);
      }
      else
      {
      	print "2012 ...";
      	return(1);
      }
      
      Python uses spaces ...
      #!/usr/bin/env python
      if True:
      	print("Hello, World")
      	return 0
      else:
      	print("2012")
      	return 1
      
      Seeing that the case for python is recognising the spaces as it's code block, it is of utmost important that the the number or spaces(or tabs) has to be equal for all the codes which falls within the same block.....
      The code below doesn't work, because the number of spaces is not equal ...
      #!/usr/bin/env python
      if True:
      	print("Hello, World")
      	return 0
      else:
      	 print("2012")		# Error, because indentation not align
      	return 1
      
      Because of this, Here're some important points ...

    3. Running Python
    4. Before we can get started, we must first know at the very least, how to make this thing run. There're 2 ways of running python.

      1. System Call Mode
      2. You write your script into a text file, with a *.py extension, and run the script Example of hello.py:-
        	#!/usr/bin/env python
        	print("Hello, World")
        	
        Running from terminal:-
        	%./hello.py
        	

      3. Interactive Mode
      4. Just invoke python interatively by calling python ...
        	%python
        	Python 2.5.1 (r251:54863, Jul 21 2007, 15:22:34)
        	[GCC 3.4.3 20060612 with Mainsoft fixes] on linux2
        	Type "help", "copyright", "credits" or "license" for more information.
        	>>> a = 'Hello, world'
        	>>> print(a)
        	Hello, world
        	>>>          
        	

    5. Help
    6. A few help that you can get.

      1. Interactive Help
      2. Start Interactive Python, and type help(topic)
        	%python
        	>>> help(str)
        	>>> a = 123
        	>>> help(a)		### Similar to help(int)
        	

      3. Python Official Page
      4. http://www.python.org/doc/

      5. Google Is Friend, Not Food ...
      6. Searching on "Python Dictionary".






    [top]

  2. Data Types and Data Structures
  3. Some of Python's useful Data Types and Data Structures ...

    1. Scalar
    2. Collection


    1. Scalar
    2. Collection
    3. A Collection is something that can store more than one scalar. 3 of the more common collection used are ...



    [top]

  4. Conditional Loops
    1. Loops


    2. Controls


    3. List Comprehension
    4. List comprehension is a very powerful feature in python.
      		animalList =  ["bear","bee","cat","fish","horse","llama"]
      		newlist = []
      		for animal in animalList:
      			if 'a' in animal:
      				newlist.append(animal)
      		### newlist ==> ['bear', 'cat', 'llama']
      		



      ... comparing the above code with this one which is equivalent below...
      		animalList =  ["bear","bee","cat","fish","horse","llama"]
      		newlist = [ animal for animal in animalList if 'a' in animal ]
      		### newlist ==> ['bear', 'cat', 'llama']
      		

      ... Do you see how neat it is? :) ...



      You can even do this ...
      		animalList =  ["bear","bee","cat","fish","horse","llama"]
      		newlist = [ animal.upper() for animal in animalList if 'a' in animal ]
      		### newlist ==> ['BEAR', 'CAT', 'LLAMA']
      		



    [top]





  5. Functions
    1. Defining A Function
    2. 		def printMyName():
      			print("My name is Lionel")
      
      		def printMyAge():
      			print("Every year 25")
      		


    3. Calling A Function
    4. 		printMyName()
      		# My name is Lionel
      		


      You can even assign your function as a reference to another variable, Like this ...
      		a = printMyName
      		a()
      		# My name is Lionel
      		
      From the above example, have you noticed something?

      By calling the function name WITH the brackets, - printMyName() -,
      we are actually executing the function itself. But, when calling the function name WITHOUT the brackets, - printMyName -,
      it is actually returning a reference to that function,
      which we can eventually assign it to any other variables.



      And with that in mind, this opens up a whole new world of creative opportunities ..... like this ...
      		my = {'name':printMyName, 'age':printMyAge}
      
      		print("What's your name?")
      		my['name']()
      
      		print("How old are you?")
      		my['age']()
      
      		### Answer:-
      		### What's your name?
      		### My name is Lionel
      		### How old are you?
      		### Every year 25
      		


      ... and like this ... :)
      		def correct():
      			print("Awesome !!! Fantastic !!!")
      
      		def wrong():
      			print("Stupid ...")
      
      		answer = [wrong, correct]
      
      		x = 5
      		answer[ True if x is 5 else False ]()
      		### Awesome !!! Fantastic !!!
      		


    5. Passing In Data
    6. 		def printMyName(name):
      			print("My name is " + name)
      
      		printMyName("Rain!")
      		### My name is Rain!
      		
      		def printMyData(name="Liang, age=25):
      			print("My name is " + name)
      			print("I am " + str(age) + " years old.")
      
      		printMyData(age=18)
      		### My name is Liang
      		### I am 18 years old.
      
      		printMyData("YeeChin", 31)
      		### My name is YeeChin
      		### I am 31 years old.
      		


    7. Returning Data
    8. 		def myName():
      			return("Lionel")
      		
      		def myData():
      			return( ['YeeChin', '25'] )
      
      		print( myName() )
      		### Lionel
      
      		[name, age] = myData()
      		print( name + " is " + age + " years old already lor ~~~")
      		### YeeChin is 25 years old already lor ~~~
      		





    [top]





  6. Dealing With Files
    1. Reading From Files
    2. 		filename = "./a.txt"
      		fh = open(filename, 'r')
      		for line in fh:
      			print(line)
      		fh.close()
      		


    3. Writing To Files
    4. 		filename = "./a.txt"
      		fh = open(filename, 'w')
      		fh.write("writing this first line into a file...")
      		fh.write("This is the 2nd line.")
      		fh.close()
      		





    [top]





  7. Classes And Objects
    1. Terminology
    2. Class: A user-defined prototype for an object that defines a set of attributes that characterize any object of the class. The attributes are data members (class variables and instance variables) and methods, accessed via dot notation.

      Class variable: A variable that is shared by all instances of a class. Class variables are defined within a class but outside any of the class's methods. Class variables aren't used as frequently as instance variables are.

      Data member: A class variable or instance variable that holds data associated with a class and its objects.

      Function overloading: The assignment of more than one behavior to a particular function. The operation performed varies by the types of objects (arguments) involved.

      Instance variable: A variable that is defined inside a method and belongs only to the current instance of a class.

      Inheritance : The transfer of the characteristics of a class to other classes that are derived from it.

      Instance: An individual object of a certain class. An object obj that belongs to a class Circle, for example, is an instance of the class Circle.

      Instantiation : The creation of an instance of a class.

      Method : A special kind of function that is defined in a class definition.

      Object : A unique instance of a data structure that's defined by its class. An object comprises both data members (class variables and instance variables) and methods.

      Operator overloading: The assignment of more than one function to a particular operator.



    3. Creating a Class
    4. 		class People():
      			"""
      			This is a documentation. 
      			A string that follows right after a block code is always a documentation.
      			It is a good practice to document all your specs/algorithm/documentation here.
      			"""
      
      			def __init__(self, n, a):
      				"""
      				This is a constructor
      				"""
      				self.name = n
      				self.age = a
      
      			def getName(self):
      				"""
      				This is a method.
      				A Method is just like a normal function.
      				It's just another way of naming it ;)
      				"""
      				return(self.name)
      
      			def setStatus(self, status):
      				"""
      				This is another method, which reads in 1 input parameter.
      				"""
      				self.status = status
      
      
      
      
      			def getStatus(self):
      				return(self.status)
      
      			def getAge(self)
      				return(self.age)
      		


    5. Constructor
    6. Every Class needs one, and only one constructor.
      A constructor is a method which binds an object to it's own class.
      Ok. I know this might sounds very confusing to some of you.
      Let's take it one step at a time.


      Whenever a user does this ...
      		yltan = People("Lionel", 25)
      		
      The above action is call Instantiating a new instance of the class(People).
      yltan is the newly created instance, or object.

      Now, when the above action takes place, the class will automatically call it's constructor method,
      which is the __init__.
      Now ....... do you see some light? ;)


      Let's take a look and see what the constructor method __init__ does:-
      		def __init__(self, n, a):
      			self.name = n
      			self.age  = a
      		


      The self.name and self.age instance variable is now being 'binded' to the instance yltan. Let's say another instance is being created:-
      		kyleong = People("Eric", 38)
      		
      The class will create another new set of self.name and self.age instance variable,
      and bind them to the newly created instance, kyleong.


    7. Methods
    8. A method is just another name for a function within a class.
      Let's take a look at the previous example:-
      			def getAge(self)
      				return(self.age)
      			def getName(self)
      				return(self.name)
      		
      Since the created instance is always having a binding with the class, we can therefore
      access to all the members of the class thru a reference.
      And that is why, all the members in a class has to be passed with a first parameter of a reference
      to it's own instance, and by convention, everyone names it as self, although it can be any variable name.

      So, now, if we want to know the age of the instances that we've created just now, all we need to do is just to
      access to the instance's respective member, and it will automatically grep the data for us:-
      		print( kyleong.getName() + " is " + str(kyleong.getAge()) + " years old .... already!" )
      		print( yltan.getName() + " is " + str(yltan.getAge()) + " years old .... only!" )
      		### Eric is 38 years old .... already!
      		### Lionel is 25 years old .... only!
      		





    [top]





  8. Useful Links
    1. Python Official Website
    2. Python Tutorial For Beginners
    3. Another Python For Beginners
    4. Dive Into Python
    5. A Collection Of Python Bloggers' Feeds
    6. Data Structure & Algorithm with Object Oriented Design Pattern in Python
    7. A Byte Of Python




    [top]





  9. Google Python Class (Video)


  10. http://www.youtube.com/watch?v=tKTZoB2Vjuk


    [top]