Practical Intorduction to Python for PS1 at Sensei Technologies

Kaivalya Rawal

Agenda:

  • Setup, Recap from Computer Programming CSF111
  • Statements, Comments, Conditionals
  • Functions
  • Documentation and Strings
  • Dictionaries and Lists
  • Iteration and Loops
  • Filter, Map, and List Comprehensions

Setup and Recap

  • Install python3, virtualenv. Libraries - ?

  • Recap of CSF111

  • Key differences: whitespace, semicolons, {}


Statements and Comments

  • arithmetic
  • variable declaration
  • comments
  • import
  • print

In [1]:
2+3


Out[1]:
5

In [2]:
2^3


Out[2]:
1

Question 1: what does 2 * * 3 do? 2^3?

Unlike C, Python doesnt require variable types to declared.


In [3]:
a = 5
b = 6
c = 'When you play the Game of Thrones, you either win, or you die.'

In [4]:
a


Out[4]:
5

In [5]:
b


Out[5]:
6

In [6]:
c


Out[6]:
'When you play the Game of Thrones, you either win, or you die.'

In [7]:
a+b


Out[7]:
11

In [8]:
a-b


Out[8]:
-1

In python, inline comments are made after a #, as opposed to the // from C. Block comments are rare, and can be made with """ """ if required. This is useful for docstrings.


In [9]:
a+c # adding an int and a string (types are implicit)


---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-9-e7db537aa383> in <module>()
----> 1 a+c # adding an int and a string (types are implicit)

TypeError: unsupported operand type(s) for +: 'int' and 'str'

Python allows you to reassign variables in the usual ways.


In [10]:
c = 1

In [11]:
a+c


Out[11]:
6

In [12]:
pi = 3.14
type(pi)


Out[12]:
float

In [13]:
type('some string')


Out[13]:
str

In [14]:
type(1)


Out[14]:
int

Question 2: Predict the output.


In [15]:
x = '125'
type(x)
y = int(x)
type(y)


Out[15]:
int

In python, we import instead of the C include. Lets import math (similar to math.h)


In [16]:
import math

In [17]:
math.pi


Out[17]:
3.141592653589793

In [18]:
math.sin(math.pi/2)


Out[18]:
1.0

To print, we use the print function in Python3, or the print statement in Python2. We'll stick with the the Python3 syntax in this notebook.


In [19]:
print('Hello')


Hello

In [20]:
'Hello'


Out[20]:
'Hello'

Question 3. What is the difference between these two?


Functions

  • Similarities with C
  • Differences from C
  • Example

Python Functions: Similarities

  • Same principle of modularisation
  • Similar parameter lists
  • Return values

Python Functions: Differences

  • Function definiton - no need to explicitly specify return types, parameter types
  • overloading vs duck typing (default parameter values)
  • docstrings
  • functions are First Class Objects

In [21]:
def factorial(n=5):
    """Function to return the factorial of a given number (Defaults to 5)"""
    if n <= 0:
        return 1
    else:
        return n*factorial(n-1)

In [22]:
print(factorial(3))
print(factorial(5))
print(factorial())


6
120
120

Question 4. Write a function to print the nth fibonacci number.

What if input is to be taken from the user?

In python, we take user input using the input() function.


In [23]:
n = input("Enter n: ")
f = factorial(int(n))
print(f)


Enter n: 5
120

Strings and Reading Documentation

The Python String class contains a lot of useful string functions. There is a lot of help available on stackoverflow forums, but the official documentation can always be found at https://docs.python.org/3.4/library/string.html.


In [24]:
s = 'You know nothing, Jon Snow!'
s


Out[24]:
'You know nothing, Jon Snow!'

The replace function can be used to replace text in a string.


In [25]:
s.replace('', '1')


Out[25]:
'1Y1o1u1 1k1n1o1w1 1n1o1t1h1i1n1g1,1 1J1o1n1 1S1n1o1w1!1'

The split function can be used to tokenize a string.


In [26]:
s.split()


Out[26]:
['You', 'know', 'nothing,', 'Jon', 'Snow!']

Question 5. Why did the previous line not show 'Kaivalya' as one of the words?

A common use of String functions is when formatting output for printing.


In [27]:
print('By the end of Game of Thrones season {}, {} Baratheons are dead.'.format(4,2.5))


By the end of Game of Thrones season 4, 2.5 Baratheons are dead.

In [28]:
print('By the end of Game of Thrones season {}, {} Baratheons are dead.'.format(5,3))


By the end of Game of Thrones season 5, 3 Baratheons are dead.

Lists and Dictionaries

Python Lists vs Java/C Arrays:

ListArray
No length attribute .length
can store multiple typessingle type
extendableneed to know length at the time of creation
offers functions to append, extend, etcneed to define own functions

In [29]:
l = [1,-2,'lannister','stark','tully','targaryen']

Lists can be accessed in powerful ways, beyond the typical index retrieval common to C and Java.


In [30]:
l[0]


Out[30]:
1

In [31]:
l[4]


Out[31]:
'tully'

In [32]:
l[-1]


Out[32]:
'targaryen'

In [33]:
l[-2]


Out[33]:
'tully'

In [34]:
l[1:4]


Out[34]:
[-2, 'lannister', 'stark']

In [35]:
l[2:]


Out[35]:
['lannister', 'stark', 'tully', 'targaryen']

In [36]:
l[:3]


Out[36]:
[1, -2, 'lannister']

Another Python data structure is a Dictionary, similar to the HashMap class from java.util.

Dictionaries store key-value pairs, where each key is unique, like a typical Ofxord dictionary.


In [37]:
d = {'wildling':'person who lives north of the wall', 
     'white-walker':'mysterious race of zombies', 
     'three-eyed-raven':'person with the ability to travel through time using weirwood trees'}

In [38]:
d


Out[38]:
{'three-eyed-raven': 'person with the ability to travel through time using weirwood trees',
 'white-walker': 'mysterious race of zombies',
 'wildling': 'person who lives north of the wall'}

In [39]:
d['wildling']


Out[39]:
'person who lives north of the wall'

Question 6. What if you try to access a dictionary with a nonexistent key value?

d['vaes-dothrak']


In [40]:
d['vaes-dothrak'] = 'capital city of the dothraki, where weapons are forbidden'

In [41]:
d['vaes-dothrak']


Out[41]:
'capital city of the dothraki, where weapons are forbidden'

Iteration and Loops

  • examples
  • generators

In Python, iteration happens with the help of iterators, similar to the Java Iterator class. While syntax is very similar to C.


In [42]:
for i in range(4):
    print(i)


0
1
2
3

In [43]:
for i in range(1,3):
    print(i)


1
2

For loops can also be used to iterate through lists without iterator functions like range.


In [44]:
for el in l:
    print(el)


1
-2
lannister
stark
tully
targaryen

In [45]:
l = [1, 5, 7, 3, 2, 9]
for i in range(len(l)):
    print('l[{}] = {}'.format(i, l[i]))


l[0] = 1
l[1] = 5
l[2] = 7
l[3] = 3
l[4] = 2
l[5] = 9

Question 7. Write an iterator that returns all even numbers between 0 and n.


In [46]:
def er(n):
    for i in range(n):
        if i % 2 == 0:
            yield i

for i in er(10):
    print(i)


0
2
4
6
8

Question 8. Use a while loop to check if the user entered a prime number.


In [47]:
def isPrime(n):
    i = 2
    while(n%i != 0):
        i += 1
    return (i == n)

isPrime(int(input("Enter a number: ")))


Enter a number: 6
Out[47]:
False

List Comprehension and Lisp Style Functional Programming

  • List comprehension examples
  • Map
  • Filter

Python supports a powerful feature known as list comprehension - iterating through lists inline to produce results. It also supports Functional programming Map and Filter idioms, despite Guido's efforts to remove them.

Suppose we want a list with numbers 0 through 2000:


In [48]:
l = [x for x in range(20)]

In [49]:
l


Out[49]:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]

Now suppose we want to remove all multiples of 7 from this list.


In [50]:
l = [x for x in range(20) if x%3 != 0]

In [51]:
l


Out[51]:
[1, 2, 4, 5, 7, 8, 10, 11, 13, 14, 16, 17, 19]

To summarize, we can write an entire 'loop' like construct within the list brackets, and Python will produce a list for us with the specified conditions.

Lets say we want to create a list which will contain points that lie on the line with equation y = 2x + 1


In [52]:
l = [[x, 2*x+1] for x in range(10)]

In [53]:
l


Out[53]:
[[0, 1],
 [1, 3],
 [2, 5],
 [3, 7],
 [4, 9],
 [5, 11],
 [6, 13],
 [7, 15],
 [8, 17],
 [9, 19]]

We can also achieve this result using Lisp Style Map and Filter, and the usual lambda <params>: <expression> syntax.


In [54]:
l = [x for x in range(20)]

In [55]:
list(filter(lambda x: x%3!=0, l))


Out[55]:
[1, 2, 4, 5, 7, 8, 10, 11, 13, 14, 16, 17, 19]

In [56]:
l = [x for x in range(10)]
list(map(lambda x: 2*x+1, l))


Out[56]:
[1, 3, 5, 7, 9, 11, 13, 15, 17, 19]


Objects and Init


In [59]:
class Person:
    pass

class Lord(Person):
    def __init__(self, add='lord'):
        self.address_by = add

class Stark(Lord):
    def __init__(self, name, gender):
        self.name = name
        if (gender == 'm' or gender == 'M'):
            if (name == 'Jon Snow'):
                super().__init__('grace')
            else:
                super().__init__('lord')

        else:
            super().__init__('lady')

class Lannister(Lord):
    def __init__(self, name, gender):
        self.name = name
        if (gender == 'f' or gender == 'F'):
            if (name == 'Cersei Lannister'):
                super().__init__('grace')
            else:
                super().__init__('lady')

        else:
            super().__init__('lord')

In [63]:
js = Stark('Jon Snow', 'm')
js.address_by


Out[63]:
'grace'

In [64]:
tl = Lannister('Tyrion Lannister', 'm')
tl.address_by


Out[64]:
'lord'

In [66]:
ss = Stark('Sansa Stark', 'f')
ss.address_by


Out[66]:
'lady'

In [ ]: