2010
10-24

python fast tutorial

This tutorial is for thous who can programing but don't know Python language. I will show how to use variables, loops, arrays, functions, and how to write scripts.

Installation

You can download python from www.python.org. After installing it you can turn on IDLE (python GUI) and executing python commands one by one, seeing results immediately.

Variables

In python you don't need to declare variables. You just use them.
  1. v = 'hello world'
  2. print i
out
hello world
you can start using that variable as numeric in any time
  1. i= 12
  2. print i
  3. i += 4
  4. print i
out:
12
4

Arrays

program:
  1. l = [1,2,3,4]
  2. print l
  3. print l[0]
  4. print l[2]
out:
  1. [1, 2, 3, 4]
  2. 1
  3. 3
Function range generate array with numebrs from one numebr to another.
  1. l = range(3,8)
  2. print l
out:
  1. [3, 4, 5, 6, 7]
In pythons tabs are important. If you don't put that tab it won't work.
  1. l = range(3,8)
  2. for i in l:
  3. print i
  4.  
out:
3
4
5
6
7

Functions

program:
  1.  
  2. def foo(ii):
  3. print 'foo function'
  4. print ii
  5. return
  6.  
  7. foo(123)
  8.  
out:
foo function
123

Scripts on Windows

You can also write python script (*.py) and execute it by double clicking on it. But if you wish to execute that scpript from command line put it to C:\windows or other direcori from path. Next go to (in case of Windows7) My Computer / Advanced system settings / Environment Variables, now edit PATHEXT by adding ;.py to it. Restart command line and you will be able to run your script from any direcory. C:\windows\hello.py
  1. print 'hello world'
  2.  
cmd
C:\>hello
hello world

Working and useful example

Ane here is more advenced working example of longlist (like in Linux). It show how to read command line arguments and read files from directory. C:\windows\ll.py
  1. import os
  2. import sys
  3.  
  4. def listDir(dir):
  5. filesList= os.listdir(dir)
  6. for f in filesList:
  7. print f
  8. return
  9.  
  10.  
  11. args= sys.argv
  12. args.pop(0)
  13.  
  14. if( len(args)==0 ):
  15. listDir('.')
  16. elif( len(args)==1 ):
  17. listDir( args[0] )
  18. else:
  19. for d in args:
  20. print ''
  21. print d+':'
  22. listDir(d)
  23.  
cmd
C:\Windows\System32\drivers\etc>ll
hosts
lmhosts.sam
networks
protocol
services

C:\Windows\System32\drivers\etc>
No Coments jet.

Leave a Reply

  ( Ctrl+Enter )