Python

import awesomeness

- Srajan and Rishabh

Why Python?

(it's really cool)

if myString.endswith(mySubString) :
	# Do something

How to do it in C++

bool endswith(string myString, string mySubString)
{
	if(myString.length()>=mySubString.length())
	{
		string mySteingEnd = myString.substr(myString.length()-mySubString.length(),mySubString.length());

		if(myStringEnd.compare(mySubString)==0)
			return true;

		else
			return false;
	}

	return false;
}

How to do it in Python

  • Easy to use/learn
  • Good support network
  • Very good documentation available
  • Code readability
  • Very powerful built in function and libraries
  • Very powerful built in data structures
  • Support for lambda function
  • Type coercion

Why Python?

More technically,

C++

  • Compiled
  • Faster
  • Type checking at compile time

Python

  • Interpreted
  • Typically slower
  • Dynamic typing

Python vs C++

int myInt = 9 ;
string myString = "Srajan" ;
myInt = 9
myString = "Rishabh"
  • Uses braces and semicolons
  • Provides only bare-minimum functions by default
  • Uses whitespace and newlines   (Forces you to write cleaner code)
  • Comes with all batteries preloaded

An example

QuickSort

C++

Python

#include <iostream>

void quickSort(int arr[], int left, int right) 
{
  int i = left, j = right;
  int tmp;
  int pivot = arr[(left + right) / 2];
 
  while (i <= j) 
  {
    while (arr[i] < pivot)
          i++;
    while (arr[j] > pivot)
          j--;
    if (i <= j) {
          tmp = arr[i];
          arr[i] = arr[j];
          arr[j] = tmp;
          i++;
          j--;
    }
  };

  if (left < j)
        quickSort(arr, left, j);
  if (i < right)
        quickSort(arr, i, right);
}
def qs(ls):
	if ls == '[]': return []
	pivot = ls[0]
	less = [x for x in ls if x < pivot]
	more = [x for x in ls if x > pivot]
	equal = [x for x in ls if x == pivot]
	return qs(less) + qs(equal) + qs(more)

Basic Syntax

Hello World!

print "Hello World!"

That's it! No need to load libraries or define functions.

Some basics :

Python code can be written in  any text editor. It just needs to be saved as a .py file.

Only one statement on one line. You can use semicolon to write multiple statement on one line, but it is usually not recommended to do so.

Variables are assigned just like in C++ , but they don't need to be previously declared or have type. 

myInt = 1
myString = "Hello"
myBool = False ; myFloat = 3.1415

Placeholders

Similar to format specifiers in C++, we use placeholders like %s and %d for string and numerical values respectively, in the print statement.(You can also use +, to seperate variables)

name = "Shantanu"
num = 420
print "%s %d" % (name,num)
# Shantanu 420
# Works as expected!

Comments

Single line comments are preceded by '#'. While multi-line comments are enclosed between ''' (three single quotes)

print "Not a comment"
# I'm  a comment
'''I'm a multi
line comment
'''

Basic operations

x, y = 3, 2 # multiple assignment
print x + y # 5 
print x - y # 1
print x * y # 6
print x / y # 1, in Python 2.7, truncates the answer
print x ** y # 9, x raised to the power of y

Type Casting 

In python, its's very easy to convert one type of data type to another. We use type casters. You can use type() to get the type of the var.

myStr = "5"
myInt = 5

print myStr + myInt
# Type error returned.
print int(myStr) + myInt
# 10
print int(5.0/3)
# 1 , float -> int 
print str(3)
# "3" , the string not the int.
print type("3")
# <type 'str'>
print type(3)
# <type 'int'>
print type(3.0)
# <type 'float'>

Input from user

In python 2.7, there are two methods to take user input. raw_input and input.

myVar = raw_input("Enter variable :")
# Will prompt user to input, and the input will be stored as string
# say we entere " 3*4 "
print myVar
# 3*4
myVar = input("Enter variable :")
# Tkes the input and tries to evaluate it, if possible
# say we input 3*4
print myVar
# 12

Conditionals

The conditionals in python are very similar to C++. Instead of using {} use indented blocks.

if a > b :
	print "a is greater than b"
elif a==b :
	print "both are equal"
else :
	print "b greater than a"

Be careful of the indentation and the colon.

Functions

In python,there is no need to mention the 'types' of arguments or return type of the function. You must define it before use, in your program. Passing of variables is 'by value' except for mutable objects (like lists).

def thankYou(name = "Srajan") :

	print "Thanks " + name
	return

thankYou("Rishabh")
# Thanks Rishabh
thankYou()
# Thanks Srajan

Classes

Classes in python, are same as in C++. Just instead of directly using member variables in member functions, a 'self' object has to be passed.

The constructor is given by  __init__()

class Dog:

    kind = 'canine'         # class variable shared by all instances

    # Constructor
    def __init__(self, namein):
        self.name = namein    # instance variable unique to each instance

d = Dog('Fido')
e = Dog('Buddy')
print d.kind                  # shared by all dogs
'canine'
print e.kind                  # shared by all dogs
'canine'
print d.name                  # unique to d
'Fido'
print e.name                  # unique to e
'Buddy'

We''ll talk about loops after a insight on lists.

Lists

The list is a versatile datatype available in Python which can be written as a list of comma-separated values (items) between square brackets. Important thing about a list is that items in a list need not be of the same type. Also, lists are mutable objects. When passed in functions as parameters, they are passed by reference.

They are similar to "vectors" as defined in the C++ STL library.

colors = ["Green","Red","Yellow","Blue"]
# Here colors is a list, with all string elements

numbers = range(2,7)
# range is an inbuilt function
# numbers = [2,3,4,5,6]

Accessing a list

print colors[0]
# Green
print colors[-1]
# Blue
print len(colors)
# 4

Iterating in a list

for color in colors :
    print color
# Green
# Red
# Yellow
# Blue

This is a for loop, and the variable 'color' is like an placeholder iterator. Basically python will place each item of the list into this variable,one at a time.

Splicing

# colors = ["Green","Red","Yellow", "Blue"]
colors[start:end] 
# items start through end-1

print colors[0:2]
# ["Green" , "Red"]

print colors[:-1]
# ["Green", "Red", "Yellow"]

print colors[0:len(colors)]
# Basically the whole list

Modifying Lists

# colors = ["Green","Red"]

colors.append("Purple")
print colors
# ["Green","Red","Purple"]

colors.insert(1,"Brown")
print colors
# ["Green","Brown","Red","Purple"]

del colors[1]
# ["Green","Red","Purple"]

colors.remove("Purple")
# ["Green","Red"]

colors.pop()
# ["Green"]

Comprehension

# Make a list of the first five even numbers.
evens = [number*2 for number in range(1,6)]
# evens = [2,4,6,8,10]

# Copying a list
b = [ a[i] for i in range(len(a)) ]

Min/Max and sum

# nums = [1,3,4,0,2]
print sum(nums)
# 10
print min(ans)
# 0
print max(ans)
# 4

# for string, min/max searches alphabetically

Making a list from another

Searching, sorting and other functions

# xyz = ["x","y","s","z"]
print xyz.index("s")
# 2
print xyz.index("A")
# ValueError "A" not in list
a = range(5,0,-1)
# a = [5,4,3,2,1]
a.sort()
# sorts in ascending/alphabetical order
print a
# a = [1,2,3,4,5]
import random
# a = range(5)
random.shuffle(a)
print a
# [0,2,3,4,1]
# a = [4,2,3,1]
a.sort()
print a
# [1,2,3,4]
# a = [2,3,4,5,1]
a.reverse()
print a 
# [1,5,4,3,2]

Tuples

Tuples are just like lists, but all of the items are of the same data type. Also tuples cannot be changed.

# declaring tuples
myTupl = (1,2,3,4)

# however, for single element tuples
myTupl = ("abc",)

# they are immutable

myTupl.append("x")    #Error
myTupl.sort()         #Error
myTupl[0] = "xyz"     #Error

newList = reversed(myTupl) 
newList = sorted(myTupl)
#No Error, reveresd/sorted return a list

# List to tuple conversion
myTupl = tuple(myList)

#splicing works
newTupl = myTupl[1:3]

Tuples are faster than lists. Can be used as dictionary keys. Tuples and lists are interconvertable.

Strings

Strings are basically a list of characters. Splicing, len and all that can be used for strings too. It has other functionality too.

Concatenation

Basically joining of two strings

# string1 = "a"
# string2 = "bc"
print string1 +string2
# abc

str = "-";
seq = ("a", "b", "c");
print str.join( seq );
# a-b-c

Find/Replace

str1 = "this is string example"
str2 = "exam"

print str1.find(str2)
# 15
print str1.find(str2, 20)
# searching after index 20
# -1

str = "this is is a string"
print str.replace("is", "was")
# thwas was was a string
print str.replace("is", "was", 2)
# 2 is the max number of replacements
# thwas was is a string
# can also use 'in'
if substr in string:
    # do this

Stripping  and splitting

a = '    b c d   '
a.strip()
# removes spaces in the beggining/end of string
print a
# 'b c d'
a = 'this,is a sentence,that i want,to break'
a.split(" ") 
# returns list of elemtts seperated by " "
print a.split(" ")
# ["this,is","a","sentence,that","i","want,to","break"]
print a.split(",")
# ["this","is a sentence","that i want","to break"]

Other functions

# string = "hello"
print string.capitalize()
# Hello

print string.islower()
# False

print string.isnumeric()
# False
# Raw strings
simpleString = "hello\n world"
rawString = r"hello\n world"

print simplestring
# hello
#  world

print rawSting
# hello\n world

# Also place a "u" instead
# of "r" for unicode strings

Raw/Unicode

Functional Programming in Python

Closure

A Closure is a function object that remembers value in enclosing space regardless of whether those scopes are present in memory or not.

def startAt(start):
	def incrementBy(inc):
		return start + inc
	return incrementBy

f = startAt(10)
g = startAt(100)

print f(1), g(2)

# 11 102

Basically, here incrementBy is a closure. In this case both f and g are references to the nested function incrementBy

Lambdas

Lambdas are anonymous throwaway functions. They are just needed where they have been created. Mostly used with other function such as filter(), map() and reduce()

def startAt(start):
	return lambda inc : start+inc

f = startAt(10)
g = startAt(100)

print f(1), g(2)

# 11 102
# Format of a lambda function
# lambda args list : expression

f = lambda x,y : x + y
print f(1,1)
# 2

Functional programming decomposes a program into a set of functions. It's programming without any assignment statements and lays emphasis on computing results rather than updating things.

map()

Basically map(), applies a particular function to each element of a list and return the answers as a list too.

# Syntax

returnedList = map(func,list)
Celsius = [39.2, 36.5, 37.3, 37.8]
Fahrenheit = map(lambda x: (float(9)/5)*x + 32, Celsius)
print Fahrenheit

# [102.56, 97.7, 99.14, 100.04]
# Here we used a lambda function

# Can be more complex
a = [1,2,3,4]
b = [17,12,11,10]
print map(lambda x,y:x+y, a,b)

# [18, 14, 14, 14]

filter()

filter() is used to filter out elements in a list using a boolean function. It returns a list, after applying the function to every element in the list.

# Syntax

returnedList = filter(boolFunc,list)
# we filter out the odd numbers

fib = [0,1,1,2,3,5,8,13,21,34,55]
result = filter(lambda x: x % 2, fib)
print result
# [1, 1, 3, 5, 13, 21, 55]

Dictionaries

Very similar to C++ un-ordered maps. They contain a set of 'key : value' pairs, such that the keys are unique, while values must be of immutable datatype.

dictionary_name = {key_1: value_1, key_2: value_2, key_3: value_3}

# Example
dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}

print dict
# {'Name': 'Zara', 'Age': 7, 'Class': 'First'}
print dict.items()
# [('Name': 'Zara'), ('Age': 7), ('Class': 'First')]
# A list of tuples

Basic operations

print dict["Age"]
# 7

# Iterating over dictionaries

for key,value in dict.items():
    print key + ":" + value
# Name:Zara
# Age:7
# Class:First

# Another iteration
for key in dict.keys():
    print key + ":" + dict[key]

# Same as before
# Modifying values

dict["Age"] = 8

# Adding values
dict["School"] = "DPS"

print dict
# {'Name': 'Zara', 'Age': 7, 'Class': 'First', 'School':'DPS'}

# Deleting elements
del dict["Age"]

print dict
# {'Name': 'Zara','Class': 'First', 'School':'DPS'}

Zipping/Unzipping

Zipping -Convert two or more lists into a list of tuples, taking the ith element of each list.

Unzipping -Convert a list of tuples, into their respective lists from which they have been zipped.

# Zipping

x = [1, 2, 3]
y = [4, 5, 6]
zipped = zip(x, y)

print zipped
# [(1, 4), (2, 5), (3, 6)]

# We can also make a dictionary

dict = { key:value for k,v in zip(x,y)}
# Unzipping

list = [(1,2), (3,4), (8,9)]
unzipped = zip(*list)
print unzipped

# [(1, 3, 8), (2, 4, 9)]

# if we want a list of lists

unzipped = map(list,zip(*list))

Basic file operations

They work a lot like they do in C++. We define a filepointer object and then use functions on that.

# Syntax
file = open("filename","mode")

# There are different types of modes
# "r" -> read only
# "w" -> write only
# "r+" -> read and write
# "a" -> append data

Reading data

myfile = open("sample.txt","r")

alldata = myfile.read()
print alldata
# prints the raw data from the file
# all data is a string!

somedata = myfile.read(numchar)
print somedata
# prints starting from the current position
# return numchar number of characters
myfile = open("sample.txt","r")


print myfile.readline()
# prints first line in file
print myfile.readline()
# prints second line

alllines = myfile.readlines()
# alllines is a list of strings
# the elements will be each line in the file
# we can iterate over these lines

for line in alllines:
    #do something with line

Writing data

f = open("sample.txt","w")

f.write("hello")
# will erase everything in file
# and will write in "hello"
f.close()

f= open("sample.txt","a")

f.write("world")
# will append this string to the files
# not affecting the previous data

Python - WnCC

By Sumith Kulal

Python - WnCC

Web and Coding Club's crash presentation to Python

  • 1,741