And you shall know the truth,
& the truth shall make you free.
John 8:32
Python Basics

Python Basics

Mar 4, 2018

Arithmetics

# Calculations achieved with numbers & arithmetic operators
print(123 / 321)
print(123 + 321)
print(123 - 321)
print(123 * 321)

# Drop decimal i.e. round result to whole no.
print(123 // 32)

# Exponents
print(3\*\*3)

String Manipulations

# Print as raw strin#G
print(r'C:/net')

# Escaping chars
print("This is the double quote symbol - \"\"")

name = "Roger Penrose"

# Print value of variable firstprint(name 5 times.
print((name + '\n') * 3)

# Print 1st letter from a string
print(name[0])

# Print 1st letter from a string from right
print(name[-1])

# Print letters from of a string from 2nd to 3rd pos
print(name[2:4])

# Print letters of a string from begining to 4th pos
print(name[:4])

# Print letters of a string from 4th pos to last pos
print(name[4:])

# Print length of a string
print(len(name))

# Reverse string
name = "George"
name = name[::-1]
print(name)

# Strip unwanted characters
name = "  George "
name2 = "George///"
name = name.strip()  # prints "George"
name2 = name2.strip("/")  # prints "George"
print(name)
print(name2)

List

players = [12, 34, 63, 10, 8, 2]

# Add item to the end of list
players.append(12)

# Delete 1st two items
players[:2] = []

# Empty list
players[:] = []

# Iterating over list values while getting the index too
m = ['a', 'b', 'c', 'd']
for index, value in enumerate(m):
    print('{0}: {1}'.format(index, value))

# Find most frequent item
test = [1, 2, 3, 4, 2, 2, 3, 1, 4, 4, 4]
print(max(set(test), key=test.count))

# List Comprehensions:

# Get list of sqaures of first 100 numbers
squares = [x**2 for x in range(1, 101)]
print(squares)

# Get remainders of squares of first 100 numbers divided by 5
remainders = [x**2 % 5 for x in range(1, 101)]
print(remainders)

# Get Movies with title starting with letter G
movies = ['Star Wars', 'Gandhi', 'Shawshank Redemption', 'Goodwill Haunting', 'Gone with the wind', 'Rear Windows']
movies2 = [title for title in movies if title.startswith('G')]
print(movies2)

# Get movies released before 2000
movies = [('Star Wars', 2000), ('Gandhi', 1999), ('Shawshank Redemption', 1990), ('Goodwill Haunting', 2001), ('Gone with the wind', 1966), ('Rear Windows', 1956)]
movies2 = [title for (title, year) in movies if year < 2000]
print(movies2)

# List as Vector - Scalar Multiplication
v = [2, -3, 1]
v2 = [x * 4 for x in v]
print(v2)

# Get cartesian product
A = [1, 3, 5, 7]
B = [2, 4, 6, 8]
cartesian_prod = [(a, b) for a in A for b in B]
print(cartesian_prod)

Set

def checkCart(cart, item):
    for i in cart:
        print(i)

    if item in cart:
        print('No need to buy ' + item)
    else:
        print("Buy " + item)
    print("\n")


cart = {"cheese", "ham", "sausage", "milk"}
checkCart(cart, 'ham')
checkCart(cart, 'oats')
checkCart(cart, 'honey')
checkCart(cart, 'cheese')


# Set operations can be performed
set_a = {1, 2, 3, 4, 5}
set_b = {2, 4, 5, 9}

# Intersection
print(set_a & set_b)

# Difference
print(set_a - set_b)
print(set_b - set_a)

# Union
print(set_a | set_b)

Tuple

# Tuple is a collection of heterogeneous data

tuple_a = (1, 2, 'a', 'b')
print(tuple_a[1])

# Tuple can contain another tuple
tuple_b = (1, 2, tuple_a)
print(tuple_b[2][2])

Dictionary

classmates = {
    'Emma': ' is an elegant girl',
    'Hannibal': ' sits besides me',
    'Roger': ' works hard',
    'Yuri': ' plays baseball'}


def getClassmates():
    for k, v in classmates.items():
        print(k + v)


getClassmates()
print(classmates['Emma'])

Branching

name = "Lucy"

if name is "Bucky":
    print("Hi Bucky")
elif name is "Lucy":
    print("Hi Lucy")
else:
    print("Please sign up.")

Loop

foods = ['cheese', 'bacon', 'beef', 'ham']


# for loop
def func1():
    for n in range(10):
        print(n)


def printAllFoods():
    for eachFood in foods:
        print(eachFood)
        print(len(eachFood))


def printSomeFoods():
    for eachItem in range(5, 12, 2):  # 5 - start, 12 - end, 2 - increment
        print(eachItem)


# While loop
def func2():
    danger = 2
    while danger < 10:
        print(danger, + "safe")  # Int - String concatenation
        danger += 1


# Can use Break & continue in loop

Functions

# Default value for parameter
def getGender(gender=None):
    if gender is 'm':
        print('Male')
    elif gender is 'f':
        print('Female')
    else:
        print(gender)


getGender('m')
getGender('f')
getGender()

# Keyword parameters
def printSentence(name='Jackson', action='makes', item='guitars'):
    print(name, action, item)


printSentence()
printSentence('John', 'bakes', 'pizza')
printSentence('Mary')
printSentence(action='repairs', name='Paul')


# Flexible parameter count
def addNums(*args):
    sum = 0
    for n in args:
        sum += n
    print(sum)


addNums(2)
addNums(3, 44.2, 1)
addNums(234, 4, -5)

# Unpacking parameters
def healthCalc(args):
    result = (100 - args[0]) + (args[1] * 2.4) - (args[2] * 2)
    print(result)


args = [23, 123, 22]
healthCalc(args)

# Returning multiple values from a function
def getAString():
    a = "George"
    b = "is"
    c = "cool"
    return a, b, c

sentence = getAString()
(a, b, c) = sentence
print(a, b, c)

Modules

import dieMod
def manyRolls(n):
string = ''
for i in range(n):
string += str(dieMod.rollDie())
print(string)
manyRolls(6)

#dieMod.py file:
import random
def rollDie():
return random.randrange(1, 6)

File Handling

# Writing to a file

fw = open('sample.txt', 'w')
fw.write('In the beginning, God created the heavens and the earth')
fw.close

# Reading from a file

fr = open('sample.txt', 'r')
text = fr.read()
fr.close()
print(text)

Web Scraping

import random
import requests
import shutil


def downloadImage(uri):
    filename = str(random.randrange(1, 10000)) + '.jpg'
    r = requests.get(uri, stream=True, headers={'User-agent': 'Mozilla/5.0'})
    if r.status_code == 200:  # request suceeds
        with open(filename, 'wb') as f:  # open, process, close w-write, b-binary/image
            r.raw.decode_content = True  # decompress file
            shutil.copyfileobj(r.raw, f)  # copyfileobj(source, destination)

downloadImage('https://images.pexels.com/photos/349758/hummingbird-bird-birds-349758.jpeg?auto=compress&cs=tinysrgb&h=350')

# shutil - https://docs.python.org/2/library/shutil.html
# requests - http://docs.python-requests.org/en/master/user/quickstart/
# open() - https://docs.python.org/3/library/functions.html#open

# Example 2 of Web Scraping
from urllib import request
goog_url = 'http://real-cgart.finance.yahoo.com'

def download_stock_data(csv_url):
    response = request.urlopen(csv_url)
    csv = response.read()
    csv_str = str(csv)
    lines = csv_str.split("\\n")
    dest_url = r'goog_url'
    fx = open(dest_url, 'w')
    for line in lines:
        fx.write(line + '\n')
        fx. close()

download_stock_data(goog_url)

Object-Orientation


#Example A:

class User:
'''
This is a simple class in Python
Class User:
'''
    def __init__(self, fullName, dateOfBirth):
        self.fullName = fullName
        self.dateOfBirth = dateOfBirth

john = User('John Bowman', '1990.02.03')
print(john.fullName)
print(john.dateOfBirth)
help(User)

#Example B
class Coordinate:
'''
This is a class for a 2d coordinate,
'''

    def __init__(self, x, y):
        self.x = x
        self.y = y

    def distance(self, other):
        xDiffSq = (self.x - other.x)**2
        yDiffSq = (self.y - other.y)**2
        return (xDiffSq + yDiffSq)**.5

    def __str__(self):
        return '(%s,%s)' % (self.x, self.y)

c = Coordinate(3, 1)
o = Coordinate(2, 2)

print(c)
str(c)
help(c)

print(c.distance(o))
print(c.distance(o))

import sys
print(sys.getsizeof(c))
print(sys.getsizeof(o))