Python Exam Notes

Section 1

Accepting Input

input command can be used to accept input from user.
It always returns a string so if you need to accept int then you need to typecast str to int.

data=input("Enter Number")

Generate random integers

random function can be used to generate random interegers, float or get random chars from a string

Generate random intergers between x & y

random.randint(x,y)

Generate float between 0 & 1

`random.random()

Get random char from a string

random.choice('string')

Conditional statements

if condition:
    do something
elif condition:
    do something
else:
    do something

Looping in python

while loop

while x < 10:
    do something

for loop

for i in range(0,3):
    do something

range(0,3) – will create list of 0-3 numbers

Formatting output

format function can be used to print str,int,float and binary
We do not need to specify the data type to print, format can figure out what the data type is

Example:

print("Printing String {}".format("Hello"))
print("Printing Integer {}".format(10))

Section 2

Scrape a webpage (download html source code a website)

urllib.request module can be used to scrape a webpage

Example:

import urllib.request
url = "www.amarchaudhari.me"
page=urllib.request.urlopen(url) // returns a file like object
pagetext=page.read().decode('utf-8')  // read data from the object and decode bytes to text

Searching for text/numbers in a html source

re module can be used to easily search text/numbers that match a regex
if text matching the regex is found then re.search will return a match group object.
– group(0) – the entire match
– group(1) – first matched sub-group
– None – if there is no match

Example:

price=re.search(r'[\d+]',pagetext)
if hasattr(price,'group'):
    do something
else:
    text not present and do something

OR
price=re.search(r'[\d+]',pagetext)
if price:
    do something

Time

import time
from time import strftime

time module can be used to get current system time.
strftime can give formatted output of current time.

Formatting Options:

Example:

from time import strftime
current_date=strftime("%Y-%m-%d")

Output:
2016-12-04