Saturday, July 9, 2011

Python as A Hobby: Getting Involved

For more information about Python and other tutorial in this series, go to static page of this tutorial here: Python as A Hobby! [ ].

In my opinion, the best way to learn a programming language is to retype examples and run it yourself. In this tutorial, I will use this method. I will give examples to let us know the way we use Python.
In the last tutorial, I have provide some examples to let you warm up with Python. In this tutorial, there will be some more complicated examples.
1. How to programming and run Python .py files
We can use terminals to program Python as we did it before, but as the programs are more complicated, we need some better way, we need to use .py files.
Now open your editor (gedit, Vim, notepad, ... ) and type this code:

#!/usr/bin/env python
#my comment
import sys
print "Welcome to microtrix.blogspot.com Python world!"
sys.stdout.write("Have you been in Microtrix or Imhades.blogspot.com")

Now, save your works as
halo.py. Open terminal, CD to the folder that you put halo.py file and type:

chmod a+x halp.py
./halo.py

You will get the result is the two string.
See, It is easy to write a python file and run .py file.
2. Beginning using functions

Now, open a new file in your favourite editor and type:

#!/usr/bin/env python
#my comment
import sys

def haloo():
  print "Welcome to microtrix.blogspot.com Python world!"
  sys.stdout.write("Have you been in Microtrix or Imhades.blogspot.com")

haloo()

Save and run this file as halo2.py. You will get the same result as the first example. But in this example we used function haloo() to print these strings.
3. Some small thing you need to know:
 a. After haloo() we need to put ":" (colon) sign.
 b. Python do not use blankets {} as a block of code sign, it use indentations. the same indentation mean the same level.
 c. You have to use chmod a+x to enable this file to be executable.
 d. import sys command has the same meaning as include command in C/C++ language.
 e. #!/usr/bin/env python is not a comment. Don't delete it or your program will generate error.

No comments:

Post a Comment