Category "Tutorials"

Raising and Handling Exceptions in Python – Python Programming Essentials

- - Tutorials

Brief Introduction

Any unexpected events that occur during the execution of a program is known to be an exception. Like everything, exceptions are also objects in python that is either an instance of Exception class or an instance of underlying class derived from the base class Exception. Exceptions may occur due to logical errors in the program, running out of memory, etc..

Common Exception Types

Class Description
Exception A base class for most error types
AttributeError Raised by syntax obj.foo, if obj has no member named foo
EOFError Raised if “end of file” reached for console or file input
IOError Raised upon failure of I/O operation (e.g., opening file)
IndexError Raised if index to sequence is out of bounds
KeyError Raised if nonexistent key requested for set or dictionary
KeyboardInterrupt Raised if user types ctrl-C while program is executing
NameError Raised if nonexistent identifier used
StopIteration Raised by next(iterator) if no element
TypeError Raised when wrong type of parameter is sent to a function
ValueError Raised when parameter has invalid value (e.g., sqrt(−5))
ZeroDivisionError Raised when any division operator used with 0 as divisor
For an example, following produces a TypeError exception
abs(‘hello world’) #expects numeric parameter but string given
Example of ValueError

Although the type of the passed parameter is correct, the value is illegitimate.

int(‘hello world’)
int(‘3.14’)

Raising an Exception

An exception can be raised from anywhere within the program though the keyword raise followed by an instance of any of the exception classes.

For example, when your program is expecting a positive integer to process but the I/O stream sent a negative integer, you could raise an Exception as such:

raise ValueError(‘Expecting a positive integer, got negative’) #instance of ValueError exception class

Handling an Exception

Now that we have talked on raising an exception, we should program such that the exception is dealt as required, else the execution of the program terminates. It is advisible to catch each exception types separately although python allows a more generic exception handling for any type of exceptions that may occur.

Examples of Common Usage:

try: 
    result = x/y
except ZeroDivisionError:
    #do as per required

Other common exception handling:

try:
    fp = open(‘sample.txt’ )
except IOError as e:
    print( Unable to open the file: , e)

Conclusion

Exceptions are an important principles of programming for any languages. It should be used wisely. On a concluding note, a try-except block can have a finally block as well. An example of use of finally can be to close a connection regardless of the successful or failed transmission of messages. Additionally, a try-except combination can have a single try block with multiple except blocks catching various classes of exception.

Follow me on github https://github.com/bhishan

Hire me for a project https://fiverr.com/bhishan

Compiling My Year With An Interpreter – Python Programming

- - Tutorials
To my dear readers, without whom this blog would have been a dead planet. Thanks for spending your valuable time here. I wish you a Happy New Year. 2015 is gone with almost an end to my sophomore year. I wouldn’t say year 2015 was any new to me than the others. Few achievements, life lessons and never ending learning curve. My very first article for 2016 will sum up my pythonic experience from 2015. I used some python throughout this semester/year to ease my life. Bear with novice’s automations :)

1. Enroll in 100% off courses at Udemy automatically.

from json import loads
from bs4 import BeautifulSoup
import mechanize
api_key = "8def4868-509c-4f34-8667-f28684483810%3AS7obmNY1SsOfHLhP%2Fft6Z%2Fwc46x8B2W3BaHpa5aK2vJwy8VSTHvaPVuUpSLimHkn%2BLqSjT6NERzxqdvQ%2BpQfYA%3D%3D"
growth_coupon_url = "https://api.import.io/store/data/a5ef05a9-784e-410c-9f84-51e1e8ff413c/_query?input/webpage/url=http%3A%2F%2Fgrowthcoupon.com%2Fcoupon-category%2F100-discount%2F&_user=8def4868-509c-4f34-8667-f28684483810&_apikey=" + api_key
br = mechanize.Browser()
br.set_handle_robots(False)
br.addheaders = [("User-agent","Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.2.13) Gecko/20101206 Ubuntu/10.10 (maverick) Firefox/3.6.13")]
sign_in = br.open("https://www.udemy.com/join/login-popup/")
br.select_form(nr=3)
br["email"] = "email@domain.com"
br["password"] = "password"
logged_in = br.submit()

growth_coupon = br.open(growth_coupon_url)
json_obj = loads(growth_coupon.read())

for course_link in json_obj["results"]:
    try:
        course_page = br.open(str(course_link["couponcode_link"]))
        soup = BeautifulSoup(course_page)
        for link in soup.find_all("a"):
            req_link = link.get('href')
            if 'https://www.udemy.com/payment/checkout' in str(req_link):
                print req_link
                br.open(str(req_link))
                print "success"
                break
    except (mechanize.HTTPError,mechanize.URLError) as e:
        print e.code

This has been my favorite automation throughout the semester. The program checks growthcoupon.com for 100% off coupon codes for paid courses offered at Udemy and enrolls me to those courses. I have uploaded the program to pythonanywhere.com which allows me to have the script run daily(for free accounts) without me having to worry about it. At this time I have over 800 courses at my Udemy account, each courses on an average costs 75$.

2. Conversation between two cleverbots

import time
from selenium import webdriver
from selenium.webdriver.common.keys import Keys

browser = webdriver.Firefox()
browser2 = webdriver.Firefox()
browser.get("http://cleverbot.com")
browser2.get("http://cleverbot.com")

time.sleep(15)

input_for_bot = browser.find_element_by_name("stimulus")
input_for_bot2 = browser2.find_element_by_name("stimulus")


output_from_bot = ""
output_from_bot2 = "Hey, friend, what's up"

for i in range(0, 200):    
    input_for_bot.send_keys(output_from_bot2)
    input_for_bot.send_keys(Keys.RETURN)
    output_from_bot = ""
    time.sleep(5)
    for elem in browser.find_elements_by_xpath('.//span[@class="bot"]'):
        output_from_bot = elem.text
    input_for_bot2.send_keys(output_from_bot)
    input_for_bot2.send_keys(Keys.RETURN)
    output_from_bot2 = ""
    time.sleep(5)
    for elem in browser2.find_elements_by_xpath('.//span[@class="bot"]'):
        output_from_bot2 = elem.text
    
    

This semester, I had to take Cognitive Science course. I enjoyed it. I had this assignment where I had to submit a page of conversation with cleverbot (www.cleverbot.com). I submitted the assignment and later decided to bridge a conversation between two cleverbots. I used selenium module in python to have this done. It was great and kind of felt like an achievement.

3. Using pyautogui before my exams

import pyautogui
import time
pyautogui.click(450,450);pyautogui.typewrite('graphicsnotes');pyautogui.press('enter')
time.sleep(2)
for i in range(107):
  pyautogui.press('right');pyautogui.press('enter')
  pyautogui.hotkey('ctrl','r');pyautogui.hotkey('ctrl','s')
  time.sleep(2)
  pyautogui.press('esc')
  time.sleep(2)

Being lazy to copy notes at class, I had to rely on photos of the notes sent by my friend. I discovered that the photos were all in landscape and were 107 pictures. I had come across pyautogui in A.I Sweigart’s course at Udemy and quickly wrote some 5-7 lines of code to open the picture and rotate the image and save it while I had my dinner. By the way I had no clue I had been enrolled in A.I Sweigart’s course until I opened my account to check which courses I had. All thanks to pythonanywhere.com which runs my program to enroll to Udemy courses on a daily basis.

4. Automate signups and making apps at Dropbox for unlimited space

from selenium import webdriver
from selenium.webdriver.common.keys import Keys

browser= webdriver.Firefox()
browser.get("https://dropbox.com/register")

list_of_inputs = browser.find_elements_by_xpath("//div/input[starts-with(@id, 'pyxl')]")

list_of_inputs[7].send_keys("first name")

list_of_inputs[8].send_keys("last name")

list_of_inputs[9].send_keys("email")

list_of_inputs[10].send_keys("password")

list_of_inputs[11].click()

password.send_keys(Keys.RETURN)

I had been involved with some people from IIT for some app ideas. We needed cloud space and agreed to use Dropbox. I had been given a bunch of emails with common password. I wrote a program in python to do the signups and later wrote a program to make apps at dropbox and get the API keys and secret keys to access the files in there. Unfortunately the project never continued for some reasons.

Overall, I had a good year but most of the time was spent at college and internship (doing mobile apps using Apache Cordova). For the new year, I will talk to my manager about switching to some python projects. My new year resolution would be to “write more codes and continue blogging about it.” Well that’s all I can think for now.

I would want some suggestions for my new year resolution. Do comment below. Once again A Happy New Year :)

Mining google search result using python – Making SEO kit with python

- - Tutorials

whatpageofsearchamion program in python

By the end of this read, you will be able to make a fully functional SEO kit where you can feed the keywords associated with certain url and the program will show the position of the url in google search. If you know some tools like “whatpageofsearchamion.com”, our program will be similar to that tool.

I was writing for a trekking based website and I had to make sure my writeup appears in a good position in google search. The keywords being competitive, I had to keep track of day to day report of the article’s status. Therefore I decided to write a simple program that would find my article’s position in google search. Continue Reading

Mining Facebook – Mining the Social Web using python

- - Tutorials

Mining data from different sources has become a trend for the past few years. The need of structured and characteristic data has lead the data miners to advice their machines to mine social data. Twitter, Google + and Facebook are some of the social networks, now serving as a mountain of behavioral data. In this post Facebook will be our Zen source and python will be the miner. Python programming language is well known for it’s capability to withdraw web data effectively and efficiently. Cutting the long story short, today we will be using Facebook Graph API through python to mine the facebook page likes for each individual adjusting in our friend list. Continue Reading

Grab alexa rank and write to google spreadsheet using python

- - Tutorials

How to grab alexa rank using python?

By the end of this read you will be able to extract alexa rank and write it to a google spreadsheet programmatically. This can be helpful for seo experts as they have to constantly analyze the alexa ranking and submit it to his/her boss in a regular basis or for personal reference. Some times you have a huge number of websites to take care of, especially when your main expertise is search engine optimization. Going to alexa’s website and writing ranks for each website is a cumbersome task to deal with. The code provided below is in python programming language. Executing the code with valid gmail id, password, spreadsheet id, worksheet id associated with the spreadsheet you want to work with will append website link and current alexa rank with date to the spreadsheet. Don’t worry about spreadsheet id and worksheet id, I will let you know on how to get these items. Continue Reading

Make a 2048 game in python – 2048 game codes in python

- - Tutorials

2048 Game in Python

By the end of this read you will be able to make a popular game 2048 on your own. Python programming language will be used to implement the logic of the game in this tutorial.2048 is a game that reached maximum popularity in my college. This started with an email from my college’s director of academics with the header 2048 : A game to make. I choose python programming language to build 2048 game. Continue Reading

How to grab certain text from gmail using imaplib and json in python

- - Tutorials

Grab certain text from gmail using python

I tried this sometimes a month ago. This article could help on extracting parts of an email(GMAIL). As I walk further I’ll show you how to extract a single word(basically sounds funny). I’ll be using python programming language in order to grab a word programmatically.

The background behind this program will drive me to explain about a practice in my college. Everyday we receive an email in a formatted manner which contains a word, its meaning, normal day use and an example sentence accommodating this word. The idea of extracting the word from email and saving it somewhere in the local machine came from one of my classmate’s. Continue Reading

NPR API Tutorial II – How to use story API to parse a story having text, audio and image from npr.org

- - Tutorials

NPR API TUTORIAL

In this NPR API Tutorial, I’ll explain you on each line of codes to parse a complete story containing text, images and audio from npr.org using the NPR API while making queries to interface using python programming language. Have you got your npr api key? If not I’ve covered how to get it in my previous post which focuses on parsing a single text story of a specific category from npr.org Find it here. This post focuses on explaining each lines of code that we’ll use to parse a complete story containing text, audio as well as images from the Nation Public Radio’s official website. Continue Reading

NPR API Tutorial – How to use the NPR API to parse a story of any topics from npr.org website

- - Tutorials

NPR API Tutorial

NPR (National Public Radio) has been providing apikeys to public in order to attract people to code and build applications that uses NPR’s application programming interface. This is a tutorial on how to use the NPR api to parse a story of any topics from npr.org website. Python programming language would be my priority in this npr api tutorial. Continue Reading