In [1]:
2+3
Out[1]:
In [2]:
2^3
Out[2]:
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]:
In [5]:
b
Out[5]:
In [6]:
c
Out[6]:
In [7]:
a+b
Out[7]:
In [8]:
a-b
Out[8]:
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)
Python allows you to reassign variables in the usual ways.
In [10]:
c = 1
In [11]:
a+c
Out[11]:
In [12]:
pi = 3.14
type(pi)
Out[12]:
In [13]:
type('some string')
Out[13]:
In [14]:
type(1)
Out[14]:
Question 2: Predict the output.
In [15]:
x = '125'
type(x)
y = int(x)
type(y)
Out[15]:
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]:
In [18]:
math.sin(math.pi/2)
Out[18]:
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')
In [20]:
'Hello'
Out[20]:
Question 3. What is the difference between these two?
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())
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)
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]:
The replace function can be used to replace text in a string.
In [25]:
s.replace('', '1')
Out[25]:
The split function can be used to tokenize a string.
In [26]:
s.split()
Out[26]:
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))
In [28]:
print('By the end of Game of Thrones season {}, {} Baratheons are dead.'.format(5,3))
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]:
In [31]:
l[4]
Out[31]:
In [32]:
l[-1]
Out[32]:
In [33]:
l[-2]
Out[33]:
In [34]:
l[1:4]
Out[34]:
In [35]:
l[2:]
Out[35]:
In [36]:
l[:3]
Out[36]:
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]:
In [39]:
d['wildling']
Out[39]:
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]:
In [42]:
for i in range(4):
print(i)
In [43]:
for i in range(1,3):
print(i)
For loops can also be used to iterate through lists without iterator functions like range.
In [44]:
for el in l:
print(el)
In [45]:
l = [1, 5, 7, 3, 2, 9]
for i in range(len(l)):
print('l[{}] = {}'.format(i, l[i]))
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)
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: ")))
Out[47]:
MapFilterPython 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]:
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]:
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]:
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]:
In [56]:
l = [x for x in range(10)]
list(map(lambda x: 2*x+1, l))
Out[56]:
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]:
In [64]:
tl = Lannister('Tyrion Lannister', 'm')
tl.address_by
Out[64]:
In [66]:
ss = Stark('Sansa Stark', 'f')
ss.address_by
Out[66]:
In [ ]: