Showing posts with label Python. Show all posts
Showing posts with label Python. Show all posts

Saturday, April 21, 2012

Error Handling Part 3


Hello everyone in this post, I will discussing something more about the Error Handling, So now we should know how to Handle Error with Try and Except, and we have also seen the use of while statement to keep our program alive.

Now here is something new, we will continue with our old script, div.py, so lets open up the script:

import exceptions
while True:
    try:
        a = int (input("Enter First Num: "))
        b = int (input("Enter Second Num: "))
        print "Result: ", a/b
        break
    except SyntaxError:
        print "Error With Your Syntax"
    except NameError:
        print "Idiot, I dont Understand You"
    except ZeroDivisionError:
        print "Integer cannot be divided by me with Zero"
    except TypeError:
        print "Hmm...Sumthingz Fishy Here"
    except KeyboardInterrupt:
        print "Hey You aborted Me"
print "------------------------"
print "[+] EOF Script"


So this worked fine in the last, and this is fine if the script a small one like this one, what if you have a huge script where you have to handle many Errors, the length of the program would just keep increasing, so we wrap the common ones or similar ones in parenthesis under one except block, remember, we you write a script, try to make the script as small as possible, and also the code should be readable, now our modified script would be:

import exceptions
while True:
    try:
        a = int (input("Enter First Num: "))
        b = int (input("Enter Second Num: "))
        print "Result: ", a/b
        break
    except (SyntaxError, NameError, ZeroDivisionError, TypeError, KeyboardInterrupt):
        print "Error: Session Aborted"
print "------------------------"
print "[+] EOF Script"

So we see here that we have placed all the exceptions errors under a single except block. so this script would display "Error: Session Aborted" for every the errors. Now this is just to show you, the way you handle the errors for your script depends on the business needs or probably the behavior of your script.

Another thing to discuss in this post, assume you are writing a huge script, its not possible to type a customed error every time for every error. So we display the error that Pythons throws, but after handling the exception. Working again with the same script:

import exceptions
while True:
    try:
        a = int (input("Enter First Num: "))
        b = int (input("Enter Second Num: "))
        print "Result: ", a/b
        break
    except (SyntaxError, NameError, ZeroDivisionError, TypeError, KeyboardInterrupt) as e:
        print "Error: ", e
print "------------------------"
print "[+] EOF Script"

On executing the script, we would get a short error message as to why the error occurred. Try this out.

Thats all for this post, hope it was informative.

Thank You!

Friday, April 20, 2012

Error Handling Part 2


Ok so now that we know about Try and Except, we will see something Interesting. Well we obviously will not want our program to get halt at any error, from last post we know how to handle the errors, now in this post I will show how to handle the errors and then continuing the script, thus giving you an idea of a full blown Python Script or Application.

Lets take the same script from the last post. So open up the div.py and we will modify the code as below:

import exceptions
try:
    a = int (input("Enter First Num: "))
    b = int (input("Enter Second Num: "))
    print "Result: ", a/b
except SyntaxError:
    print "Error With Your Syntax"
except NameError:
    print "Idiot, I dont Understand You"
except ZeroDivisionError:
    print "Integer cannot be divided by me with Zero"
except TypeError:
    print "Hmm...Sumthingz Fishy Here"
except KeyboardInterrupt:
    print "Hey You aborted Me"

Now thats the main script, which can only handle the errors, but wont keep continuing the script, to achieve this we need a while loop with break statements. So our modified code would be as below:

import exceptions
while True:
    try:
        a = int (input("Enter First Num: "))
        b = int (input("Enter Second Num: "))
        print "Result: ", a/b
        break
    except SyntaxError:
        print "Error With Your Syntax"
    except NameError:
        print "Idiot, I dont Understand You"
    except ZeroDivisionError:
        print "Integer cannot be divided by me with Zero"
    except TypeError:
        print "Hmm...Sumthingz Fishy Here"
    except KeyboardInterrupt:
        print "Hey You aborted Me"
print "------------------------"
print "[+] EOF Script"

On executing the script:

>>>
Enter First Num:
Error With Your Syntax
Enter First Num: str
Hmm...Sumthingz Fishy Here
Enter First Num:
Hey You aborted Me
Enter First Num: 40
Enter Second Num: 0
Result:  Integer cannot be divided by me with Zero
Enter First Num: lol
Idiot, I dont Understand You
Enter First Num: 40
Enter Second Num: 2
Result:  20
------------------------
[+] EOF Script
>>>

So let me explain the script, I have kept the main try and except blocks inside a While loop, and the condition says, while True, means keep doing it, until you find a break statement, A break statement exits a loop. And inside the try block I have placed the break statement, so that the loop can exit only if the try is a success, if its not a success and if there is any error, it goes to the except statement, and since the except statements doesn't have a break statement, the script would loop again because of the while True condition. True is a builtin keyword. You can also replace True with 1. So it also be coded as

while 1:
     #scripts
This would give the same result. I prefer typing True, because it looks more Pythonist.

Okay, so I guess this post should be an interesting one. Hope you are learning Python from the blog. Keep Practicing, and don't forget to check my next post.

Thank You!

Thursday, April 19, 2012

Error Handling Part 1


Hello Everyone, in this post, I will discuss, about handling Error In Python. Well as a programmer, we want our script or application to run absolutely fine, without any error or warnings, making the program halt due to the error.

So It is the most important part of any programming language to handle errors. So Lets see how to Handle errors, but before lets see what all error can a simple program have:

print "Division Script"
a = int (input("Enter First Num: "))
b = int (input("Enter Second Num: "))
print "Result is: ", a/b

Save this as div.py and when we execute the program, remember we are focusing on getting Errors, so we will Generate Errors.

>>>
Division Script
Enter the First Num: 10.1
Enter the Second Num: 2
Result is:  5
>>> ============= RESTART ===============
>>>
Division Script
Enter the First Num: str

Traceback (most recent call last):
  File "C:/Python27/div1.py", line 2, in <module>
    a = int(input("Enter the First Num: "))
TypeError: int() argument must be a string or a number, not 'type'
>>> ============= RESTART ===============
>>>
Division Script
Enter the First Num: lol

Traceback (most recent call last):
  File "C:/Python27/div1.py", line 2, in <module>
    a = int(input("Enter the First Num: "))
  File "<string>", line 1, in <module>
NameError: name 'lol' is not defined
>>> ============= RESTART ===============
>>>
Division Script
Enter the First Num: 40
Enter the Second Num: 0
Result is:

Traceback (most recent call last):
  File "C:/Python27/div1.py", line 4, in <module>
    print "Result is: ", a/b
ZeroDivisionError: integer division or modulo by zero
>>> ============= RESTART ===============
>>>
Division Script
Enter the First Num:

Traceback (most recent call last):
  File "C:/Python27/div1.py", line 2, in <module>
    a = int(input("Enter the First Num: "))
  File "<string>", line 0
   
   ^
SyntaxError: unexpected EOF while parsing
>>> ============= RESTART ===============
>>>
Division Script
Enter the First Num:

Traceback (most recent call last):
  File "C:/Python27/div1.py", line 2, in <module>
    a = int(input("Enter the First Num: "))
KeyboardInterrupt
>>>
So here we have quite a few Error, which we never looked at earlier while programming. now we will handle those errors.So we will modify our script:

import exceptions <-- Module to Handle Error and Warning Exceptions
try:
    a = int (input("Enter First Num: "))
    b = int (input("Enter Second Num: "))
    print "Result: ", a/b
except SyntaxError:
    print "Error With Your Syntax"
except NameError:
    print "Idiot, I dont Understand You"
except ZeroDivisionError:
    print "Integer cannot be divided by me with Zero"
except TypeError:
    print "Hmm...Sumthingz Fishy Here"
except KeyboardInterrupt:
    print "Hey You aborted Me"

And when we execute this script, and try to generate errors, we will get the customed messages, rather than a Traceback Error.

Ok let me explain the script first, first we imported the Module, then our main script is inside the try block, try block asks Python to try something, and if it fails or generates some error, this error will be passed to the except blocks, and if a matched except block is found, it will execute the codes under that particular except block. Also note here, I am very specific about the error types because This is a small program, and the chances of Error are limited here, what I could have done is, I could have made a global except block that would have handled any error. But its actually a bad practice, to house all errors under one except statement. Just To show you, I could have done this:

import exceptions <-- Module to Handle Error and Warning Exceptions
try:
    a = int (input("Enter First Num: "))
    b = int (input("Enter Second Num: "))
    print "Result: ", a/b
except:
    print "There is Some Error"

So this would show the same error for every kind of errors, But we don't want that, okay so lets run our modified script:

>>> ============= RESTART ===============
>>>

Enter First Num: 40
Enter Second Num: 0
Result:  Integer cannot be divided by me with Zero
>>> ============= RESTART ===============
>>>
Enter First Num: str
Hmm...Sumthingz Fishy Here
>>> ============= RESTART ===============
>>>
Enter First Num: lol
Idiot, I dont Understand You
>>> ============= RESTART ===============
>>>
Enter First Num:
Hey You aborted Me
>>> ============= RESTART ===============
>>>
Enter First Num:
Error With Your Syntax
>>>

Okay, This is all in this post, will discuss more with Error Handling in the next Post. I hope this was interesting. Don't Forget to check my next post.

Thank You!

Wednesday, April 18, 2012

Network Handling Part 3


Hello Everyone, in this post I will discuss about accessing FTP Servers with Python.

To show you some examples of FTP, I will use the 'ftp.redhat.com'

Before I proceed, a small note here, till now we have seen that we import modules by typing "import modulename", well thats correct, but with this statement we are importing all the functions of the Module, even those which we are not using in the program, so its RAM consuming. there Is another way to import specifically whatever function we need from the Module by typing "from Modulename import specific_function"

>>> from ftplib import FTP
>>> ftp =FTP('ftp.redhat.com') <--creating a connection to redhat FTP server
>>> ftp.login() <--since logging in without username and password, there is no arguments passed here, if the login had to use a username and password, the statement ud have been ftp.login('username' 'password')
'230 Login successful.'
>>> d = 'redhat/linux' <--setting a directory path
>>> ftp.cwd(d) <--change the directory
'250 Directory successfully changed.'
>>> print ftp.dir() <--To see the contents of the directory
-rw-r--r--    1 ftp      ftp           131 Dec 20  2005 README
drwxr-xr-x    3 ftp      ftp          4096 Feb 21 05:44 beta
drwxr-xr-x    6 ftp      ftp          4096 Jun 14  2007 eal
drwxrwsr-x   14 ftp      ftp          4096 Jul 25  2011 enterprise
drwxr-xr-x    2 ftp      ftp          4096 Feb 12  2006 preview
drwxr-xr-x    2 ftp      ftp          4096 Dec 03  2008 rawhide
drwxrwsr-x    4 ftp      ftp          4096 Sep 26  2008 updates
None
>>> help(ftp)
[Try this out, as its a huge output, try to understand the functions of the Module]

There is another FTP library that is yet more powerful and robust, but external is the chilkat Module, you can go to http://www.chilkatsoft.com/ and have a look.

Well thats all for this Post. Keep Practicing, I hope you are enjoying them. Don't forget to check my next post.

Thank You!

Tuesday, April 17, 2012

Network Handling Part 2

Hello Everyone, Lets now continue our Journey, with few more examples of Network Handling in Python.

First I would like to introduce you to geturl() of urllib Module

Lets Open up the Python Shell

>>> import urllib
>>> site = "http://microsoft.org"
>>> find = urllib.urlopen(site)
>>> find.geturl()
'http://www.microsoft.com/en-us/default.aspx'
>>> # geturl() tell us the redirected url

Another Function that you would like to know is urlretrieve(), which saves a copy of any webpage, but the only thing is that it would not display any images when you open up the copied html doc. but the external links on the copied web page would just work fine.

>>> urllib.urlretrieve('http://www.python.org', 'C:/files/python.html')

So the above line would save a copy of the website in C:/files named python.html

So , we have seen the basics of accessing the web pages with Python, there are some more functions which I will discuss on the next post.

Hope this was Interesting, and Don't forget to check my next Post.

Thank You!

Monday, April 16, 2012

Network Handling Part 1

Hello Everyone, welcome to the next phase of Python, where now you will discuss about handling webpages and networks. Again, its not possible for me to provide you with each and every minute details, because in programming field, you yourself have to be creative. But I will provide you with the basics so that you can start with and go in the right direction.

By now I assume while you reading this post, that you are already aware of File Handling and other Functions of Python that has been discussed so far.

So lets get started.

For dealing with web based resources and networks, Modules that are most of the times handy are: urllib, urllib2, ftplib, httplib, etc etc, these are the standard Python Modules, but for dealing with heavy web based scripts you need to go out on the internet and search for Modules that satisfies your scripting needs.

Ok so let me show you a small script to access the  resources on a shared folder on a network, ofcourse you need to have the accessing rights from the host that you will run the script.

Lets open up the Python Shell 

>>> import os
>>> location = os.listdir('\\\\192.168.10.110\\share') <---connects to the location
>>> f = open('\\\\192.168.1.106\\share\\test.txt', 'w')
>>> f.write('hey there')
>>> f.close

This was a small script through which I could access the Local Shared Folder I am sure if you have been reading my posts carefully, you can modify this to be flexible and used by anyone. Notice I have hard coded here the path, so to make it flexible that user should be able to enter any path they like.
Note: Notice here that I have used four backslash, as to access the resource we use two backslash, we use another two backslash as escaping, if you do not escape it, you would run into an error.

Let me also show you another script through which you can access the raw HTML of any webpage.

import urllib, os
wn = raw_input("Website name: ")
connect = urllib.urlopen(wn) <--Creates a connection to the webpage
for lines in connect:
    print lines

I have saved it as connect.py and when I execute it,

>>>
Website name: http://www.google.com

[Output Not Pasted Here, as Its a huge Output]

>>>

Well thus far, you should now have some knowledge and idea about accessing web resources with Python. Hope this post was helpful.

Again, if you go out on internet for Modules, make sure its a trusted site, and use the Modules after reading and understanding it, well more on network handling on future posts.

Thank You!

Sunday, April 15, 2012

File Handling In Python IV

Hello everyone, this post would not be a long one, as all the basics has been discussed about file handling.

This is just a quick review of some more File Handling Module that I could not relate to the earlier posts.

Lets get started.

>>> import os
>>> os.name
'nt'
>>> import sys
>>> sys.platform <--More Defined Way To Know About a Host OS
'win32'
>>> dir(sys)
['__displayhook__', '__doc__', '__excepthook__', '__name__', '__package__', '__stderr__', '__stdin__', '__stdout__', '_clear_type_cache', '_current_frames', '_getframe', '_mercurial', 'api_version', 'argv', 'builtin_module_names', 'byteorder', 'call_tracing', 'callstats', 'copyright', 'displayhook', 'dllhandle', 'dont_write_bytecode', 'exc_clear', 'exc_info', 'exc_traceback', 'exc_type', 'exc_value', 'excepthook', 'exec_prefix', 'executable', 'exit', 'flags', 'float_info', 'float_repr_style', 'getcheckinterval', 'getdefaultencoding', 'getfilesystemencoding', 'getprofile', 'getrecursionlimit', 'getrefcount', 'getsizeof', 'gettrace', 'getwindowsversion', 'hexversion', 'long_info', 'maxint', 'maxsize', 'maxunicode', 'meta_path', 'modules', 'path', 'path_hooks', 'path_importer_cache', 'platform', 'prefix', 'py3kwarning', 'setcheckinterval', 'setprofile', 'setrecursionlimit', 'settrace', 'stderr', 'stdin', 'stdout', 'subversion', 'version', 'version_info', 'warnoptions', 'winver']
>>> sys.version
'2.7.2 (default, Jun 12 2011, 15:08:59) [MSC v.1500 32 bit (Intel)]'
>>> sys.winver
'2.7'
>>> sys.subversion
('CPython', '', '') <--Python is Officially known as CPython, other version is Jython.
>>> sys.api_version
1013
>>> sys.getwindowsversion()
sys.getwindowsversion(major=5, minor=1, build=2600, platform=2, service_pack='Service Pack 2')
>>> sys.getsizeof('C:/files')
29
>>>

Play around with the sys module, type help(sys.any_method_of_sys) To get a detailed report of the Functions.

Well, Some Of You now may be thinking, how to handle some other type of file like an Image File, or say pdf, well, for these, Pythons Inbuilt Library is not enough, You have to go out on the web, to search for the Modules.

Make a Note Here, Whenever You Use Modules from the web, make sure to check that the Module is coded for Python 2 series, because Python 3 has got different syntax.

1. For Images: You need to look for PIL(Python Imaging Library) Take help of Google, as I dont want to spoon feed for everything.

2. MS Office: You need a Module named pywin32, or Python Office(especially meant for excel worksheets)

3. PDF: You need a Module named gfx, found under swftools

And a lot more are there, remember, Python is kinda open source, where codes are developed by any one and everyone. But before using any Module, make sure You use a Module from a trusted site, one good source is stackoverflow.

Now, do you remember I said when we create our own Modules we save it in places where Python looks for, one place i mentioned was Pythons root folder. There is one place and recommended as a standard Pythonist, you should always save the modules in site-packages. Example in my case its:

C:\Python27\Lib\site-packages, to verify, on the Python Shell, click on File>>Path Browser>>Expand the [+] C:\Python27\Lib\site-packages, and you should be able to see any new module that you import there.

Okay, so this was pretty much that you need to fire up your Python Instinct, hope this was helpful, Keep Practicing.

Don't forget to check my next post.

Thank You!

Saturday, April 14, 2012

File Handling In Python III

Hello everyone, in this post we will discuss more about File Handling with Python..

Okay, so far I have discussed, how to create, append, read and close a File, also discussed about how to check the current directory and change directory, how to make new folder, etc.

In this post, lets start by showing you how to delete a folder and continue with few more functions.

Lets fire up the Python Shell..

>>> os.getcwd()
'C:\\Python27'
>>> os.chdir('C:\\files')
>>> os.listdir(os.curdir)
['i m siiting here.jpg', 'Looping with disctionary.txt', 'morefiles', 'Printout.docx', 'py1.html', 'Python post march20.txt', 'Python Post March21.txt', 'Python Post March22.txt', 'Python Post March25.txt', 'python post19th.txt', 'python.html', 'Python27march.txt', 'sub', 'test.html', 'test1.html', 'tkinter1.pdf', 'whiskey.html']
>>> for files in os.listdir(os.curdir):
             print files

   
i m siiting here.jpg
Looping with disctionary.txt
morefiles
Printout.docx
py1.html
Python post march20.txt
Python Post March21.txt
Python Post March22.txt
Python Post March25.txt
python post19th.txt
python.html
Python27march.txt
sub
test.html
test1.html
tkinter1.pdf
whiskey.html
>>> # Now lets say I want to delete the test.html file
>>> os.remove('test.html') <--- Deletes a File
>>> Note: the parameter it takes is path, but since I am in the same directory, I just entered the file name, But If You want to Delete some thing on a different folder you need to type in the exact path, like C:\\folder\\subfolder\\file
>>> for files in os.listdir(os.curdir):
             print files

   
i m siiting here.jpg
Looping with disctionary.txt
morefiles
Printout.docx
py1.html
Python post march20.txt
Python Post March21.txt
Python Post March22.txt
Python Post March25.txt
python post19th.txt
python.html
Python27march.txt
sub
test1.html
tkinter1.pdf
whiskey.html
>>> #test.html file is missing, means it has been deleted, now lets see how to rename a file, we will rename, we will rename test1.html to sample.html
>>> os.rename('test1.html', 'sample.html')
>>> for files in os.listdir(os.curdir):
             print files

   
i m siiting here.jpg
Looping with disctionary.txt
morefiles
Printout.docx
py1.html
Python post march20.txt
Python Post March21.txt
Python Post March22.txt
Python Post March25.txt
python post19th.txt
python.html
Python27march.txt
sample.html
sub
tkinter1.pdf
whiskey.html
>>>

We have another Function, that helps to walk through a directory, suppose u have a folder, where you have some files, and also few sub folders, where you have some more files. So os.walk() helps to recursively walk through the files. Lets check it out.

>>> path = 'C:\\files'
>>> for root, dirs, files in os.walk(path):
             print root
             print dirs
             print files
             print " "
           
C:\files
['morefiles', 'sub']
['i m siiting here.jpg', 'Looping with disctionary.txt', 'Printout.docx', 'py1.html', 'Python post march20.txt', 'Python Post March21.txt', 'Python Post March22.txt', 'Python Post March25.txt', 'python post19th.txt', 'python.html', 'Python27march.txt', 'sample.html', 'tkinter1.pdf', 'whiskey.html']

C:\files\morefiles
[]
['log.txt', 'myfile.txt', 'RHDSetup.log']
 
C:\files\sub
[]
['animated Pictures.txt', 'ASCII conversion Java.txt', 'average calculator 2 java.txt', 'back track wifi wpa hack.txt', 'backtrack.txt', 'backtrack2resolve.txt', 'bangladesh hackers friend.txt', 'bangladesh site hacked.txt', 'batch virus.txt', 'botnet.txt', 'CBT Sites.txt', 'CEH Linux commands.txt', 'CEHv7.txt', 'check how many times a character appears in word_java.txt', 'computer korner post.txt', 'constructor explained by Onty.txt', 'convertRHELtoCentos.txt', 'cpp keyloger.txt', 'crackinf for this software.txt', 'Cracking tut.txt', 'davemate2bhacked.txt', 'Deface and Shell.txt', 'defacepageCreator.txt', 'DummiesJava.txt', 'facebook emo added.txt', 'FootprintingCEH.txt', 'forum.txt', 'good site.txt', 'hack note.txt', 'hackers shell tool.txt']

 >>> #So what I asked Python is, please look for all the files in the folder named files under C: and display the path, display sub folders and then display the files.

 Yet Another Module, that I would like to present here, is the glob Module, that helps to display files matching a Pattern or regular expression. Lets check it out.

 >>> import glob
 >>> for files in glob.glob('C:\\files\\*.txt'):
             print files

   
C:\files\Looping with disctionary.txt
C:\files\Python post march20.txt
C:\files\Python Post March21.txt
C:\files\Python Post March22.txt
C:\files\Python Post March25.txt
C:\files\python post19th.txt
C:\files\Python27march.txt
>>> for files in glob.glob('C:\\files\\*.pdf'):
             print files

   
C:\files\tkinter1.pdf
>>> for files in glob.glob('C:\\files\\*.jpg'):
             print files

   
C:\files\i m siiting here.jpg
>>>

So you see that you can almost do anything and everything with Python, If you know Him well. Well I guess this was informative and Interesting and one of the important chapters in Python, So practice it well, and Don't Forget to check my next post.

Thank You.

Wednesday, April 11, 2012

File Handling In Python

Hello Everyone, I guess This Post should be interesting as now we are in a position to go out of the Python Shell and touch the files of a host operating system.

In this post I will discuss about Handling File System. This is a Vast Topic where the inbuilt Python Module is not enough to get all our jobs done, but for starting point, and showing you how to use them, the inbuilt modules of Python works fine. The Word Module should not be unfamiliar with you in this post, and here onwards. And From here onwards I also assume that you know about Lists, tuples, Dictionary and all the stuffs that I posted Earlier.

Lets first start with how to create a file. So I am Going To show how to create a text file under the root directory of a Windows OS, i.e the C drive.

For a text file we should know, how to create, append, read and close a text file. We will work in the Python Shell, its same when you write a script in any text editor. Python interpreter would process and handle the scripts in same way.

The Basic Syntax for creating, appending, and reading is: variable_object_name = open('Relative Path', 'mode')

1. To create a text file named example.txt

>>> myFile = open('C:/example.txt', 'w') <--w means we want to write or create a text file
>>> myFile.write('This is the First Line\n')
>>> myFile.write('This is the second Line\n')
>>> myFile.writelines(''' This is blah blah blah......
....
...
....
This is the End of the Text file.\n''')
>>> myFile.close()

So first we have created a file in writing mode, and have written some lines, and finally closed the file.
write --> To write Lines in a text file line by line or as a paragraph
writelines --> To write a bunch of lines or paragraphs or to write a List we use writelines.

>>> sample = ['Python', 'Learning', 'is', 'Fun']
>>> myFile = open('C:/example.txt', 'a') <-- a means we want to append to the file
>>> myFile.writelines(sample)
>>> myFile.close()
>>>

2. To read the example.txt file

>>> myFile = open('C:/example.txt', 'r') <-- r means we want to read the file
>>> #By default, if we do not type the mode, python assumes it to be in read mode.
>>> myFile.read()
'This is the First Line\nThis is the second Line\n This is blah blah blah......\n....\n...\n....\nThis is the End of the Text file.\nPythonLearningisFun'
>>> myFile.seek(0)
>>> #seek(position) takes the python cursor to where-ever we want, since I will show some more read Functions, i have taken the cursor to the starting position.
>>> myFile.readline()
'This is the First Line\n'
>>> myFile.readline()
'This is the second Line\n'
>>> myFile.readline()
' This is blah blah blah......\n'
>>> myFile.readline()
'....\n'
>>> myFile.readline()
'...\n'
>>> myFile.readline()
'....\n'
>>> myFile.readline()
'This is the End of the Text file.\n'
>>> myFile.readline()
'PythonLearningisFun'
>>> myFile.readline()
''
>>> #readline --> reads line by line
>>> >>> myFile.seek(0)
>>> myFile.readlines()
['This is the First Line\n', 'This is the second Line\n', ' This is blah blah blah......\n', '....\n', '...\n', '....\n', 'This is the End of the Text file.\n', 'PythonLearningisFun']
>>> #readlines almost similar to read the difference is, it returns a List
>>> myFile.read()
'This is the First Line\nThis is the second Line\n This is blah blah blah......\n....\n...\n....\nThis is the End of the Text file.\nPythonLearningisFun'
>>> myFile.readlines()
[]
>>> myFile.seek(0)
>>> myFile.readlines()
['This is the First Line\n', 'This is the second Line\n', ' This is blah blah blah......\n', '....\n', '...\n', '....\n',
'This is the End of the Text file.\n', 'PythonLearningisFun']
>>> myFile.close()
>>>

To get a display in a readable manner, we use the For Iterator,

>>> myFile = open('C:/example.txt', 'r')
>>> for lines in myFile.readlines():
              print lines

   
This is the First Line

This is the second Line

 This is blah blah blah......

....

...

....

This is the End of the Text file.

PythonLearningisFun
>>> myFile.close()

Note: It is important to close a file, when you open it for any reason.

Now If You look in the C: Drive, you would see an example.txt file created.

Hope this was interesting, Practice it, play around with the functions, and Don't forget to check my next post.

Thank You.

Tuesday, April 10, 2012

More On Modules

Hello Everyone, in this post, I Will Discuss something more about Modules, its very interesting, so lets get started.

So far we know what a Module is and how to use them. But as We know that Modules are created by Python Users, for some specific outputs or results. Well If I make a Module and use it in my programs, I am aware of the functions in that Module. But if I use a Module created by someone else or rather the Python Builtin Modules, how am I supposed to know what are the functions of the Modules. And what does the Module do.

Well lets create a Module and try to understand with the example. The Same applies for any other Module that you will come across in Your Python Life.

Lets create a Module:

#SimpleMath Module
def __doc__():
    print "This is a simple Math Module Which Can Add Or Subtract"
def add(x,y):
    z = x + y
    return z
def sub(x,y):
    z = x - y
    return z

Save it as simplemath.py under C:/python27

Now On the Python Shell, what can you to do understand the Module,

>>> import simplemath
>>> #First we need to import the Module and then proceed
>>> dir(simplemath)
['__builtins__', '__doc__', '__file__', '__name__', '__package__', 'add', 'sub']
>>> #dir(modulename) --> Lists the functions and variable name used in the Module
>>> help(simplemath)
Help on module simplemath:

NAME
    simplemath - #SimpleMath Module

FILE
    c:\python27\simplemath.py

FUNCTIONS
    add(x, y)
   
    sub(x, y)


>>> #help(modulename) - returns a detailed report of the Module
>>> help(simplemath.add)
Help on function add in module simplemath:

add(x, y)

>>> #help(modulename.functionname) -->displays the specific report of the function
>>> simplemath.__doc__()
This is a simple Math Module Which Can Add Or Subtract
>>> #modulename.__doc__() --> found on almost all standard Module, which returns a short description about what the Module does.

Well This was just a simple Module that I created for explanation, there exists a Huge Library Of Modules. And to understand any Module these steps helps every-time.

Few Builtin Modules that you would Like To Practice with are: math, urllib, urllib2, system, etc

Check them out, and try to understand them as Modules are used heavily in Python Scripts.

Thank You and Don't Forget to check My Next Post.

Monday, April 9, 2012

Importing Modules

Hello everyone, in this post I will discuss about Modules and how to import Modules.

What are Modules?

Modules are functions created by people that displays a certain output when imported.

Ok so far we know how to make a Class and Functions and how to use them, that's good, but the problem is once the Python window is closed, we cannot use the Functions created in a program for a different Program.

So here comes Modules, we make Modules and save it in places where Python looks for when we import the Module, Pythons root directory is one of the location where it searches for modules. So with this technique, we can use a Module with as many different programs we want.

Lets check this small example.

Open the IDLE, and the IDLE text editor by pressing Ctrl+n

#Sample Module
def test():
    print "I am a Sample Module"

And now save it as sample.py directly in the Python27 Directory(C:\Python27) and close the editor. So what we saved is a Module, and the name of the Module is sample, and this module has a test function that prints "I am a Sample Module"

Now on the IDLE

>>> import sample <--- Module Imported
>>> sample1.test()
I am a Sample Module
>>>

Now even if we restart the Python Shell or make a new Program, and if we Import the sample module, and call the test function, we would get the same output.

Hope this makes the Basics clear about the Modules. Now lets make a small Program That would import add, subtract modules in any program.

For this we need to make two Modules, Add and Subtract, and to be very basic lets say these modules works with two numbers. So here we Go.

1.

#The Add Module which finds the addition of two numbers
def add(x,y):
    z = x + y
    return z

Save it as add.py, so the module name is add

2.

#Module for Subtraction
def sub(x,y):
    z = x - y
    return z

Save it as sub.py, so the module name is sub

Now that we have created two modules we can use them with any programs, below is an example program

3.

#This is a Program where we import modules and work
import add
import sub
#Note if we are importing more than one module, we usually write them in one statement, separating them with a comma, so we can rewrite this as import add, sub
choice = input("Enter 1 for add, 2 for subtract: ")
x = input("Enter the First Number: ")
y = input("Enter the Second Number: ")
if choice==1:
    r = add.add(x,y)
    print "The Addition of ", x, " and ",y, " is ",r
else:
    r = sub.sub(x,y)
    print "The Subtraction of ", x, " and ",y, " is ",r
raw_input("Press Enter To Exit")

Outputs:

>>>
Enter 1 for add, 2 for subtract: 1
Enter the First Number: 23
Enter the Second Number: 43
The Addition of  23  and  43  is  66
Press Enter To Exit
>>>=========== RESTART ==============
>>>
Enter 1 for add, 2 for subtract: 2
Enter the First Number: 40
Enter the Second Number: 20
The Subtraction of  40  and  20  is  20
Press Enter To Exit
>>>

Okay so I Hope this should make the things clear about what a Module is, and how to work with it.

Practice it, as this is one of the main concept used in Python scriptings.

Thank You and Don't Forget to check the next post.

Sunday, April 8, 2012

Constructors

Hello everyone, in this post I will discuss something about Class.

So far, we know almost the basics of how to use a Class and how to make an object and how to use them.

But most of the time, it is required to do something automatically, as soon as the object is created, We will go in details about the usage in our later posts, as of now, we have to know how to make it and remember it, so that when we use it in making scripts we don't get confused.

This is the concept of an inbuilt python method known as constructor. So when a constructor method is created inside a class, and then when an object is created to use the class, Python looks if there is any constructor in the class, if it finds one, it automatically executes the constructor.

NOTE: This is the difference, previously when we used a method, we had to call the method from the class with a DOT Operator. But for a Constructor, we don't have to do so, as it automatically executes the constructor.


The built method for defining a Constructor is: def __init__(self): [Anything in this method is automatically executed and its a double underscore

Lets check a small example:

>>> class Test:
            var = "This is just a Variable"
            def __init__(self):
                     print "I Got executed even before I was called"
            def callMe(self):
                     print "I Am Lazy, You have to Call Me to See Me"

       
>>> ObjectTest = Test()
I Got executed even before I was called
>>> ObjectTest.var
'This is just a Variable'
>>> ObjectTest.callMe()
I Am Lazy, You have to Call Me to See Me
>>>

So I Hope Makes Everything Clear about what A Constructor is.

Practice it, and Don't forget to check my next Post.

Thank You.

Friday, April 6, 2012

Inheriting Multiple Parent Class

Hello Everyone, This is a short post on how to inherit multiple Parent Class to a Child Class.

So far, we know how to inherit single Parent Class, So Another Important Thing You should know is how to add multiple Parent Class.

Lets check the example:

>>> class parentCar:
              car1 = "I am Car1"
              car2 = "I am Car2"
              car3 = "I am Car3"

   
>>> class parentBike:
              bike1 = "I am Bike1"
              bike2 = "I am Bike2"
              bike3 = "I am Bike3"

   
>>> class childTransport(parentCar, parentBike): <--Parent Class Inherited
              car4 = "I am Car4"
              bike4 = "I am Bike4"

   
>>>
>>> transport = childTransport() <--Object Created To use the Child Class
>>> transport.car1
'I am Car1'
>>> transport.car3
'I am Car3'
>>> transport.car4
'I am Car4'
>>> transport.bike1
'I am Bike1'
>>> transport.bike3
'I am Bike3'
>>> transport.bike4
'I am Bike4'
>>>

I hope this is pretty much self explanatory, you just need to remember this, as it helps a lot while scripting.

Thank You and Dont Forget to check my Next Post.

Thursday, April 5, 2012

Parent Class and Child Class

Hello Everyone, In this post I will discuss about the Parent Class and Child Class.

From earlier posts we already know how to make a class, and use the class by creating objects. That is good but how would you feel when you have to make several class, that are almost similar to each other. That would be a pain to type same codes and statements again and again, isn't it??

Here comes the concept of Parent Class and Child Class or also known as Super Class and Sub Class.

In this concept, we make a Parent class, and the Child Class inherits the attributes or characteristics of the Parent Class.

How do we do that? Lets check with an example:

>>> class autoMobileParent:
               car1 = "This is Maruti 800"
               car2 = "This is Mercedez Benz"
               bike1 = "This is Bajaj Pulsar"
               bike2 = "This is Harley Davidson"

   
>>> autoMobileParent.car1
'This is Maruti 800'
>>> autoMobileParent.car2
'This is Mercedez Benz'
>>> autoMobileParent.bike1
'This is Bajaj Pulsar'
>>>

Okay we have created a Parent Class, now we will make Child Class and make Make Some Objects.

>>> class childCar(autoMobileParent):  <--Here we inherited the Parent Class
                  car3 = "This is a Van"

   
>>> car = childCar()
>>> car.car1
'This is Maruti 800'
>>> car.car2
'This is Mercedez Benz'
>>> car.car3
'This is a Van'
>>>

>>> class childBike(autoMobileParent):  <--<--Here we inherited the Parent Class
               bike3 = "This is Royal Enfield"

Lets make another, just for fun..
  
>>> bike = childBike()
>>> bike.bike1
'This is Bajaj Pulsar'
>>> bike.bike2
'This is Harley Davidson'
>>> bike.bike3
'This is Royal Enfield'
>>>

Notice here, that even if we did not create car1, car2 or bike1, bike2 for the respective child class, they inherited it from the Parent Class.

Okay so I hope Super Class and Sub Class should be clear with you now, practice it, and Don't forget to check my next post.

Thank You!

Wednesday, April 4, 2012

Class and Methods

Hello Everyone, in this post I will discussing about the Classes used in OOP In some more details.

From the last post, we already know how a class looks like and what all we can have in a Class, like Methods, Arguments.

So lets create a Class and then I will explain what happens, and Remember that a Class is a Blueprint, that should have the capability to be used with multiple objects, so our class has to be flexible.

>>> class area:
            def sq(self, l,b):
                  self.l = l
                  self.b = b
                  area = self.l*self.b
                  return area
>>>

So the first line is the class header, and the name of the class is area. Second line we have defined a method name sq which takes 2 arguments l and b.

Hold on , Hold on, I see here three arguments self, l and b, so how do you say it takes 2 arguments, You must be thinking this isn't it??

Ok the mystery reveals, self is a kind of temporary variable that hold the object name that will be used with the class, remember I said that the code has to be flexible. so (self, l, b) here means (objectname, l and b) so we have made the method dynamic as it can use any object and relate to it.

Next line we have self.l = l, which means objectname.l = l of the objectname(We are letting Python know that l means the l of the objectname) and same is for the next line too.

Next we have the formula, which calculates the area by self.l*self.b(which means l of the object*b of the object) and assigns it to a variable area.

Finally we have the return statement which returns the value of the area.

Now how do we use the class? To use the class, we have to create objects, so lets make 2 objects, one for square and one for rectangle.

>>> square = area()
>>> # we have create an object named square
>>> square.sq(10,10)
100
>>> # we call the method of the object with the DOT(.) operator, object.method, in this case square.sq(10, 10) by passed the value of l and b
>>> # self.l = 10, and self.b = 10 and after calculating the area it returned the value
>>> # as i said self.l means objectname.l, so if we now try square.l it should return the value 10
>>> square.l
10
>>> # You see, it returned 10, now if we use another object, what would happen, will these values of square object change? No, it wont, because, our self argument helps to keep them separate.
>>> rect = area()
>>> rect.sq(15, 25)
375
>>> square.l
10
>>> rect.l
15
>>>
>>> square.b
10
>>> rect.b
25
>>>

And We can create as many objects we want using one class.

NOTE: Again self, is important in class, otherwise its useless, the whole purpose of class gets void, so whenever we have a method in a class, the argument self is a must, even if it does not take any argument.

An example:

>>> class example:
              def p(self):
                          print "You see its must"

       
>>> test = example()
>>> test.p()
You see its must
>>>

So I hope This Makes the concept clear, Practice It Well, Try To Understand them properly, as slowly we are diving down into Python,

Thank You!

Monday, April 2, 2012

More About Functions

Hello everyone, in this post I will discuss something more about functions..

Okay till now we have seen how to make a function and set the arguments that would take Tuple or Dictionary.

Ex:

>>> def sample1(name, *girlFrnds, **ages):
           print name
           print girlFrnds
           print ages

   
>>>
>>> sample1('Whiskey', 'Aini', 'Sweety', 'Rose', Aini=22, Sweety=21, Rose=23)
Whiskey
('Aini', 'Sweety', 'Rose')
{'Rose': 23, 'Sweety': 21, 'Aini': 22}
>>>

A Short Program, that prints the user name, girl friends name, and their name with ages.

Ok, now lets see, how to pass a Tuple Or Dictionary to a Function Directly.

Lets check with Tuple First.

>>> def sample2(*names):
            print names

   
>>> girlfriends = ('Aini', 'Sweety', 'Rose')
>>> sample2(*girlfriends)
('Aini', 'Sweety', 'Rose')
>>>

Now lets see Dictionary

>>> def sample3(**ages):
           print ages

   
>>> girl_age={'Aini':22, 'Sweety':21, 'Rose':23}
>>> sample3(**girl_age)
{'Rose': 23, 'Sweety': 21, 'Aini': 22}
>>>

Its very simple, practice it, just remember the way how it works, because we will need them in future posts.

The main difference is, when we are speaking about Tuple in function, its a one star(*) and Dictionary has two star(**)

Thank You, And Don't Forget to check my next post.

Sunday, April 1, 2012

Using Dictionary in Functions

Hello everyone, in this post I am going to discuss how to use dictionary in a function.

From the last post, we came to know how to create a function, and define a Tuple in a function that would take multiple values.

Now lets see how to use a dictionary.

Open up the Python Shell

>>> def sample(name, *characteristics, **marks):
           print name
           print characteristics
           print marks

   
>>> sample('Whiskey', 'Good', 'Lovely', 'Kind', 'Poizon')
Whiskey
('Good', 'Lovely', 'Kind', 'Poizon')
>>>

Well this was what we learnt from the last post, now lets see how to use a dictionary type in the function.

Whenever we use a dictionary type we need to indicate by double * (**) symbol before the variable.

Example:

>>> def sample(name, *characteristics, **marks):
           print name
           print characteristics
           print marks


   
>>> sample('Whiskey', 'Good', 'Lovely', 'Kind', 'Poizon', maths=76, science=78, computer=80)
Whiskey
('Good', 'Lovely', 'Kind', 'Poizon')
{'maths': 76, 'science': 78, 'computer': 80}
>>>

Well Note here, something, Python will automatically understand that a certain argument getting passed is a Dictionary value when it encounters the "=" symbol.

Also Note Something, we cannot change the order of values that we pass to a function.

Ex:

>>> def sample(name, *characteristics, **marks):
           print name
           print characteristics
           print marks

   
>>> sample(maths=76, science=78, computer=80, 'Whiskey', 'Good', 'Lovely', 'Kind', 'Poizon' )
SyntaxError: non-keyword arg after keyword arg
>>>

So we see here it gave an error, so we have to be careful about the order in which the values are passed.

So, This is all about the basics of playing with user defined functions, Practice it well, as while programming
every now and then its used to achieve certain outputs.

Thank You, and Don't Forget to check My next Post.

Friday, March 30, 2012

Multiple Parameters


Hello Everyone, in this post, we will check how to add multiple parameters to a functions, we need to this trick many a time while programming a script..

Okay lets get started.

First lets make a function

>>> def python(name):
           print name


>>> python('PythonGame')
PythonGame
>>> python('Python', 'Game')

Traceback (most recent call last):
  File "<pyshell#12>", line 1, in <module>
    python('Python', 'Game')
TypeError: python() takes exactly 1 argument (2 given)
>>>

Well what happened is, we made a function take takes only one argument, and if we pass, more than one argument, it gives an error, as it cannot handle more than one.

Now, lets see how can we make it work, i.e to accept multiple arguments..

>>> def python(*name):
           print name

>>> python('Python', 'Game', 'Snake')
('Python', 'Game', 'Snake')
>>>

It it took three arguments and worked absolutely fine, and returned a Tuple. So this is the trick, we need to add a * symbol while defining the argument of the function.

Now, to clear the confusion, if you have any, lets check one more example

Lets say, we have been given a task, where the output should display software/application name along with platform supported.

>>> def soft(name, *support):
          print name
          print support

>>> soft('Python', 'Windows, Linux, MAC')
Python
('Windows, Linux, MAC',)
>>> soft('Python', 'Windows', 'Linux', 'MAC')
Python
('Windows', 'Linux', 'MAC')
>>>

Well I guess this should be clear with you, and these posts are very important, please try to understand them well.

Thank You and Don't forget to check my next post.

Wednesday, March 28, 2012

How to add Default Parameters


Hello Everyone, In This post we will see how to add default parameters to functions that we define in a Python Script. You might have noticed I have started using the word script, instead of Python Program, Yes, technically Python Programs are known as Scripts, which are heavily used in Desktop Applications and Web Development Applications. As a matter of fact, Web Browser Opera is made in Python, so as the application Google Earth, there are many more examples, we are yet very far from those topics.

Lets get back to the topic.

Suppose we write a script and define some functions, and the script is used by system administrators or network administrators for some automated tasks, like bulk copying or deleting or sharing, etc, etc. So what if the user dsnt inputs anything for the parameters of the functions defined? The script will choke and We don't want that isn't it?

So here is what we do, we add some default values to the functions:



>>> def name(first,last):
              print '%s  %s' % (first,last)

>>> f = 'Python'
>>> l = 'Script'
>>> name(f,l)
Python Script
>>> name()

Traceback (most recent call last):
  File "<pyshell#8>", line 1, in <module>
    name()
TypeError: name() takes exactly 2 arguments (0 given)
>>>

So we see here, if there is no arguments passed for the function, it choked

What we can do is, just modify and add a default value to the arguments of the functions:

>>> def name (f_name='Fatal', l_name='Error'):
              print "%s %s" % (f_name, l_name)

   
>>> name()
Fatal Error
>>>  name('Hello', 'World')
Hello World
>>> name(f,l)
Python Script
>>>


So we see here that, when no arguments is passed, it returns or displays the default value.

And when argument is passed, it displays the arguments that has been passed.


So I hope This Has been Informative To you, Practice it, And Don't forget to check the next Post.

Thank You.

Tuesday, March 27, 2012

How To Build Own Functions


Hello everyone, in this post we will see how to make our own functions, till now we have used functions that were built-in to Python. But many a times while writing a script we need to repeat certain things over and over again, wish there was something that would make life easy...Yes this is where building own functions comes handy.


How do you create own functions?

Its simple, we just need the key word def and the syntax is:

def function_name(arguments):
    statements

Note: User-Defined Functions are valid only for one script. Function created for one script is not valid for other script.

Now lets check out some created functions

>>> def var_a(x):
            return "Whats Your Social Security Number, "+x+"?"

>>> print var_a("Python")
Whats Your Social Security Number Python?

So whenever we call the defined function "var_a" with an argument, it returns the result after executing the codes under functions.

Okay, so by now I am guessing why no one asked how to clear the shell while working with the Python Shell. When I was learning python, I wanted to know how to clear the window of the Python Shell. In Windows Command Shell, when we type "cls" it clears the Window, In Linux Shell when we type "clear" it clears the window, but unfortunately, Python doesn't have such command, but programmers are genius, there is a trick which can clear up the window for you, and guess what its by the user-defined function, lets check it out how.

>>> def clearpy():
             return "\n"*50

>>> print clearpy()

So when we call the defined function clearpy(), as expected it will print 50 new blank lines, thus making the Shell looking decent and clean.

Okay, So I Hope This was Informative For you, practice this and make sure you will not be surprised when I use the def functions in future posts.

Thank You!