Programming

Python : Modules, Errors, Exceptions and Stuff

Thanks for being patient and learning all that basics without asking how its going to help you to achieve the ultimate goal Getting Shit Done. So this is the last tutorial where I am telling you some more basics, we will do the real thing later.

No! Python isn’t limited to what I taught you. Most of the books and courses out there teach a lot of things which may seem useless to you, I will teach you the same things but I will teach you all that boring stuff while you are learning how to build a crawler or port scanner.

Lets begin!

Comments : Lets save our memory for ideas

print 'Fuck World' #it prints Fuck World

Output:

Fuck World

The code should have produced an error because #it prints Fuck World is out of single quotes. Nope, we just used a comment here. Comment is that part of code which doesn’t get executed or read. They are used by programmers to keep track of what is what and help others understand the program.

Inserting a comment is easy. Just write whatever you want after a # (hash) sign. If you want to write a multi-line comment you can do that as follows:

a = 12 #this is first number
b = 13 #this is second number
"""
This is a comment where I am trying to waste some space
so this comment can take more than one line. It will not get
executed.
"""
print a + b #its prints the sum of a and b

That’s pretty easy.

Handling Errors

If you are following this course and have been trying to code your own stuff then you might have came across several errors. Errors should be fixed otherwise the code won’t run! But as the Zen Of Python says,

Special cases are not special enough to break the rules.

Do you want to know what that means? Take a look here:

python basics

I created a simple program which asks the user to input a number and multiplies it with 2 but as you can see the user entered x which is not a number and hence the program ended up throwing an error. This program is perfect, however the user is stupid. So we deal with this kind of Special Cases? Before we get there lets differentiate between errors and exceptions (special cases).

  • Error: An error is caused when the program is written wrong. The programmer might have misplace a variable name or forgot to add : at the and of an if statement etc. It basically means the programmer fucked up the code.
  • Exception: An exception is cause when the syntax of program is right but an error occurs while executing it, take a look at the above example. Exceptions may occur when you thought your code is perfect but people will say the programmer fucked up the code even when its not your fault.

So lets handle this exception by using try and except statements:

num = raw_input('Enter a number to find its double: ')
try: #try to execute the code
    num = int(num)
    print 'Double of number is : %i' % (num * 2)
except: #if an exception occurs, do this
    print 'Enter a number next time.'

try statement contains the code which needs be protected from exceptions, while the except tells the program what to do when an exception is occurred. Now lets try running our exception proof code:
error handling python
Great! We did it!
But always keep in mind that you should always try to fix things. try and except statements are to handle special cases and not for hiding your stupid programming skills. Just one more obvious thing, you can’t use a try statement without a except statement and vice versa.

This program knows you are gay

I wrote a program which keeps copying what you say unless you enter i am gay

print """This is a program which will keep copying what you say,
unless you say 'i am gay'
"""
a = 1
while a == 1:
    user = raw_input('Type: ')
    if user == 'i am gay':
        print 'Thanks for accepting'
        quit()
    else:
        print user

Lets break down the code:

  • We use three (double quotes) in the print statement so we can print multiple lines. If you don’t want use three single/double quotes, use the /n (newline) character.
  • We defined a variable in the second line which has a value of 1.
  • After that, we initiated a while loop which will keep running as long as the value of a is 1 which means if the value of a never changes, it will run forever.
  • Then we are asking use to type something and assign the value of user input to a variable named user
  • After that, we using an if statement to check if the value of user variable is i am gay, if it is then our program prints Thanks for accepting and exits. So quit() is used to exit a program? Yes we will explore exiting programs in a while.
  • If the if condition is not satisfied i.e. user entered something else than i am gay we print the variable user which holds the value of whatever the user entered. At this point, the program reaches its end but the value of a is still 1 which satisfies the condition of our while loop and hence the loop gets executed again.

I hope you understood whatever I did here. If no then read all the previous tutorials again and if yes lets move on to the last topic of this chapter.

Exiting Programs and Modules

So yeah we used quit() statement to exit the program but there are better ways. If you only want to stop a loop (for or while) use the break statement and not quit().

Except from quit() there are several other ways to exit a program:

  • quit() : Exits the program
  • exit() : Its exactly same as quit(), just the name is different
  • sys.exit() : It too exits the program but it requires sys module
  • os._exit() : Something you shouldn’t use unless you know what is does. If you are curious use google

So I just mentioned something called a module. What is a module?

In simple words, modules are programs that can be used in another programs. Confused?

Let me give you can example, there are many people who want to build something like JARVIS but all of them are building different programs. Like some are working on the ability to recognize objects, some are working on how to give commands via voice, some are working on how to make it speak etc. But in order to build Jarvis, they would have to design a single program which would have all these abilities. So instead of putting everything in a single python file, they kept the files separated and built a program which can use all these abilities on demand.

Now if someone else wants to build a program which needs a feature of converting text to speech, he can use that single file created by developers of Jarvis instead of writing such program.

Many people have created programs that you can use in your program and are available for free, these programs are called modules or libraries. Some modules come pre-installed with your python interpreter and there are thousands of modules that you can install manually.

Importing modules is simple. For example, I said that to use sys.exit() you should have sys module. Sys module comes pre-installed so you don’t need to install it, just import it like this:

import sys

print 'in next chapter we will build a SQLi scanner'
sys.exit()

Note: There was no need to exit this program but I had to show you how to import modules so…

Thats all for now. Keep Learning! Keep Coding!

Next Chapter >>

Also Read: Exploit, Vulnerability, Payload : Explained For Beginners


10 Comments

Click here to post a comment

Subscribe Now

Subscribe for free and get latest articles delivered right into your inbox.

Thank you for subscribing.

Something went wrong.

Categories

>-----ADVERTISEMENT-----<