Python Training at VMWare - Day 2

Feb 26-28, 2018 Vikrant Patil

These notes are available online at http://notes.pipal.in/2018/vmware-feb-python

© Pipal Academy LLP

Day 1 | Day 2 | Day 3

In [3]:
def fibseries(n):
    """
    generates list of fibonacci numbers less than n
    """
    
    prev, current = 1,1
    series = []
    
    while prev < n:
        series.append(prev)
        prev, current = current, current+prev
        
    return series
In [4]:
fibseries(100)
Out[4]:
[1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
In [6]:
fibs = fibseries(100)
fibs
Out[6]:
[1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
In [7]:
sqrfib = []
for f in fibs:
    print(f,end=",")
1,1,2,3,5,8,13,21,34,55,89,
In [8]:
sqrfib = []
for f in fibs:
    sqr = f*f
    sqrfib.append(sqr)
In [9]:
sqrfib
Out[9]:
[1, 1, 4, 9, 25, 64, 169, 441, 1156, 3025, 7921]
In [10]:
names = ["Alice","Elsa","Harry","Alex"]
In [11]:
for name in names:
    print(name.upper())
ALICE
ELSA
HARRY
ALEX
In [12]:
person = {"name":"Alice","email":"alice@example.com","website":"http://alice.example.com"}
In [13]:
for key in person:
    print(key)
name
email
website
In [14]:
for key in person:
    print(person[key])
Alice
alice@example.com
http://alice.example.com
In [15]:
for key in person:
    print(key, person[key])
name Alice
email alice@example.com
website http://alice.example.com
In [16]:
for char in "just for checking for loops over string":
    print(char, end=",")
j,u,s,t, ,f,o,r, ,c,h,e,c,k,i,n,g, ,f,o,r, ,l,o,o,p,s, ,o,v,e,r, ,s,t,r,i,n,g,
In [17]:
for color in (256,256,0):
    print(color)
256
256
0
In [18]:
for i in range(10):
    print(i, end=",")
0,1,2,3,4,5,6,7,8,9,
In [19]:
for p in [2,3,5,7,11,13]:
    print(p, end=",")
2,3,5,7,11,13,
In [22]:
for item in set("just for checking for loops over sets"):
    print(item, end=",")
i,p, ,k,l,c,v,r,f,u,h,s,o,n,j,g,e,t,

problems

  • Write a python script ls.py which mimics unix command ls approximately. it prints every filename from given directory on new line.
    python ls.py .
    day1.ipynb
    day1.html
    module.py
    module1.py
  • Write a function product which finds proudct of all items from given collection of numbers.
  • Write a function factorial which computes factorial of given number
In [23]:
list(range(5))
Out[23]:
[0, 1, 2, 3, 4]
In [24]:
list(range(2,6))
Out[24]:
[2, 3, 4, 5]
In [26]:
n= 5
list(range(1,n+1))
Out[26]:
[1, 2, 3, 4, 5]
In [27]:
%%file ls.py
import sys
import os

def ls(dirpath):
    files = os.listdir(dirpath)
    for file in files:
        print(file)
        
if __name__=="__main__":
    if len(sys.argv)==1:
        ls(os.getcwd())
    else:
        ls(sys.argv[1])
Writing ls.py
In [28]:
!python ls.py
.ipynb_checkpoints
push
day1.ipynb
module.py
day2.ipynb
day2.html
add1.py
day3.ipynb
add2.py
module1.py
day3.html
Makefile
__pycache__
add.py
day1.html
ls.py
In [29]:
!python ls.py /tmp
systemd-private-07acfb7fd2f84c96bbfed6bcdd6b55c5-rtkit-daemon.service-AO0a4o
.XIM-unix
systemd-private-07acfb7fd2f84c96bbfed6bcdd6b55c5-colord.service-Tf93jp
ssh-sYRlH00Tkf2j
.font-unix
config-err-6gRILk
.ICE-unix
.X11-unix
.X0-lock
.Test-unix
mintUpdate
In [30]:
def product(numbers):
    p = 1
    for n in numbers:
        p *= n
    return p

def factorial(n):
    return product(range(1,n+1))
In [32]:
product([3,4,5,6])
Out[32]:
360
In [33]:
factorial(5)
Out[33]:
120
In [36]:
def print_primes(n):
    """
    print all primes less than or equal to n
    """
    for i in range(1,n+1):
        for j in range(2,i):
            if i%j==0:
                break
        else:
            print(i,end=",")
In [37]:
print_primes(20)
1,2,3,5,7,11,13,17,19,
In [38]:
def squares(numbers):
    sqrs = []
    for n in numbers:
        sqrs.append(n*n)
    return sqrs

def evens(numbers):
    def even(x):
        return x%2==0
    
    e = []
    for n in numbers:
        if even(n):
            e.append(n)
    return e
    
In [39]:
squares([2,3,4,5])
Out[39]:
[4, 9, 16, 25]
In [40]:
evens(range(10))
Out[40]:
[0, 2, 4, 6, 8]
In [41]:
fibs
Out[41]:
[1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
In [43]:
fibs[:2] # take first two
Out[43]:
[1, 1]
In [44]:
fibs[2:] # drop first two
Out[44]:
[2, 3, 5, 8, 13, 21, 34, 55, 89]
In [45]:
fibs[2:5] # start at 2nd index end at 5th index(excluding)
Out[45]:
[2, 3, 5]
In [46]:
fibs[1:6:2] ## start at 1st index end at 6th index(excluding) at step of 2
Out[46]:
[1, 3, 8]
In [47]:
fibs[:]
Out[47]:
[1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
In [50]:
fibs[:-1] #drop last one
Out[50]:
[1, 1, 2, 3, 5, 8, 13, 21, 34, 55]
In [51]:
fibs[:-2] # drop last two
Out[51]:
[1, 1, 2, 3, 5, 8, 13, 21, 34]
In [52]:
fibs[::-1]
Out[52]:
[89, 55, 34, 21, 13, 8, 5, 3, 2, 1, 1]
In [53]:
def is_palindrom(word):
    return word == word[::-1]
In [54]:
is_palindrom("madam")
Out[54]:
True
In [55]:
is_palindrom("hello")
Out[55]:
False

problems

  • Write a function split_at which splits given list in two parts breaking original list at given index
In [56]:
def split_at(items, n):
    return items[:n],items[n:]
In [58]:
split_at(list(range(10)), 3)
Out[58]:
([0, 1, 2], [3, 4, 5, 6, 7, 8, 9])

problem

  • Write a function find_extension to find extension of given file.
    >>> find_extension("xyz.tar.gz")
    "gz"
In [59]:
s = "do geese see god"
In [60]:
s[100]
---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
<ipython-input-60-4868bd16d438> in <module>()
----> 1 s[100]

IndexError: string index out of range
In [61]:
s[:100]
Out[61]:
'do geese see god'

list comprehensions

In [63]:
[i*i for i in range(7)]
Out[63]:
[0, 1, 4, 9, 16, 25, 36]
In [65]:
[i*i*i for i in range(7)]
Out[65]:
[0, 1, 8, 27, 64, 125, 216]
In [66]:
[w.upper() for w in names]
Out[66]:
['ALICE', 'ELSA', 'HARRY', 'ALEX']
In [68]:
[i for i in range(7)]
Out[68]:
[0, 1, 2, 3, 4, 5, 6]
In [69]:
[i for i in range(7) if i%2==0]
Out[69]:
[0, 2, 4, 6]
In [70]:
[i for i in range(1,6)]
Out[70]:
[1, 2, 3, 4, 5]
In [72]:
t = [[i*j for i in range(1,6)] for j in range(1,11)]
In [73]:
t
Out[73]:
[[1, 2, 3, 4, 5],
 [2, 4, 6, 8, 10],
 [3, 6, 9, 12, 15],
 [4, 8, 12, 16, 20],
 [5, 10, 15, 20, 25],
 [6, 12, 18, 24, 30],
 [7, 14, 21, 28, 35],
 [8, 16, 24, 32, 40],
 [9, 18, 27, 36, 45],
 [10, 20, 30, 40, 50]]
In [74]:
t[0]
Out[74]:
[1, 2, 3, 4, 5]
In [75]:
t[-1]
Out[75]:
[10, 20, 30, 40, 50]
In [77]:
t[0][-1] # last item from 0th row
Out[77]:
5

problems

  • Write a function to generate list of python files from given directory
    >>> listpy(os.getcwd())
    ['module.py','module1.py','add.py']
  • Write a function factors which finds all factors of given number.
    >>> factors(5)
    [1,5]
    >>> factors(6)
    [1,2,3,6]
  • make use of fact that prime number has only two factors 1 and self to write a function is_prime which determines if given number is prime or not.
  • Write a list comprehension to generates primes using above function.
In [78]:
def listpy(path):
    return [f for f in os.listdir(path) if f.endswith(".py")]
In [80]:
import os
listpy(os.getcwd())
Out[80]:
['module.py', 'add1.py', 'add2.py', 'module1.py', 'add.py', 'ls.py']
In [81]:
def factors(n):
    return [i for i in range(1,n+1) if n%i==0]
In [82]:
factors(5)
Out[82]:
[1, 5]
In [83]:
def is_prime(n):
    return factors(n)==[1,n]
In [84]:
def primes(n):
    return [p for p in range(1,n+1) if is_prime(p)]
In [85]:
primes(20)
Out[85]:
[2, 3, 5, 7, 11, 13, 17, 19]

problem

  • Generate a unit matrix of dimension 5x5 using list comprehensions.
  • sum all multiples of 7 or 11 below 1000
In [86]:
[[i*j for i in range(5)] for j in range(5)]
Out[86]:
[[0, 0, 0, 0, 0],
 [0, 1, 2, 3, 4],
 [0, 2, 4, 6, 8],
 [0, 3, 6, 9, 12],
 [0, 4, 8, 12, 16]]
In [87]:
[[i==j for i in range(5)] for j in range(5)]
Out[87]:
[[True, False, False, False, False],
 [False, True, False, False, False],
 [False, False, True, False, False],
 [False, False, False, True, False],
 [False, False, False, False, True]]
In [88]:
[[int(i==j) for i in range(5)] for j in range(5)]
Out[88]:
[[1, 0, 0, 0, 0],
 [0, 1, 0, 0, 0],
 [0, 0, 1, 0, 0],
 [0, 0, 0, 1, 0],
 [0, 0, 0, 0, 1]]
In [89]:
[[1 if i==j else 0 for i in range(5)] for j in range(5)]
Out[89]:
[[1, 0, 0, 0, 0],
 [0, 1, 0, 0, 0],
 [0, 0, 1, 0, 0],
 [0, 0, 0, 1, 0],
 [0, 0, 0, 0, 1]]
In [90]:
[[{True:1,False:0}[i==j] for i in range(5)] for j in range(5)]
Out[90]:
[[1, 0, 0, 0, 0],
 [0, 1, 0, 0, 0],
 [0, 0, 1, 0, 0],
 [0, 0, 0, 1, 0],
 [0, 0, 0, 0, 1]]
In [91]:
t
Out[91]:
[[1, 2, 3, 4, 5],
 [2, 4, 6, 8, 10],
 [3, 6, 9, 12, 15],
 [4, 8, 12, 16, 20],
 [5, 10, 15, 20, 25],
 [6, 12, 18, 24, 30],
 [7, 14, 21, 28, 35],
 [8, 16, 24, 32, 40],
 [9, 18, 27, 36, 45],
 [10, 20, 30, 40, 50]]
In [92]:
t[0]
Out[92]:
[1, 2, 3, 4, 5]
In [93]:
t[0][0]
Out[93]:
1
In [95]:
t[0][:]
Out[95]:
[1, 2, 3, 4, 5]
In [96]:
def column(data, n):
    rows = len(data)
    return [data[i][n] for i in range(rows)]
In [97]:
column(t, 0)
Out[97]:
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
In [98]:
t
Out[98]:
[[1, 2, 3, 4, 5],
 [2, 4, 6, 8, 10],
 [3, 6, 9, 12, 15],
 [4, 8, 12, 16, 20],
 [5, 10, 15, 20, 25],
 [6, 12, 18, 24, 30],
 [7, 14, 21, 28, 35],
 [8, 16, 24, 32, 40],
 [9, 18, 27, 36, 45],
 [10, 20, 30, 40, 50]]
In [99]:
column(t, 1)
Out[99]:
[2, 4, 6, 8, 10, 12, 14, 16, 18, 20]
In [102]:
def transpose(data):
    cols = len(data[0])
    return [column(data, i) for i in range(cols)]
In [101]:
transpose(t)
Out[101]:
[[1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
 [2, 4, 6, 8, 10, 12, 14, 16, 18, 20],
 [3, 6, 9, 12, 15, 18, 21, 24, 27, 30],
 [4, 8, 12, 16, 20, 24, 28, 32, 36, 40],
 [5, 10, 15, 20, 25, 30, 35, 40, 45, 50]]
In [103]:
def reverse(item):
    return item[::-1]
In [104]:
def rotate90clockwise(data):
    cols = len(data[0])
    return [reverse(column(data, i)) for i in range(cols)]
In [105]:
rotate90clockwise(t)
Out[105]:
[[10, 9, 8, 7, 6, 5, 4, 3, 2, 1],
 [20, 18, 16, 14, 12, 10, 8, 6, 4, 2],
 [30, 27, 24, 21, 18, 15, 12, 9, 6, 3],
 [40, 36, 32, 28, 24, 20, 16, 12, 8, 4],
 [50, 45, 40, 35, 30, 25, 20, 15, 10, 5]]

Iteration patterns

In [106]:
for i in primes(20):
    print(i, end=",")
2,3,5,7,11,13,17,19,
In [113]:
for i in reversed(primes(20)):
    print(i, end=",")
19,17,13,11,7,5,3,2,
In [114]:
reversedprimes = reversed(primes(20))
In [115]:
for p in reversedprimes:
    print(p, end=",")
19,17,13,11,7,5,3,2,
In [116]:
for p in reversedprimes:
    print(p, end=",")
In [117]:
multiline = """
one
two
three
four
five
"""
In [118]:
lines = multiline.strip().split()
In [119]:
lines
Out[119]:
['one', 'two', 'three', 'four', 'five']
In [122]:
for index,line in enumerate(lines):
    print(index, line)
0 one
1 two
2 three
3 four
4 five
In [126]:
for ind,value in enumerate(lines):
    print(ind, value)
0 one
1 two
2 three
3 four
4 five
In [123]:
names = ["Elsa","Elisa","Alex","David"]
surnames = ["Frozen","Hacker","Lion","Beazley"]
In [124]:
for n, s in zip(names, surnames):
    print(n,s)
Elsa Frozen
Elisa Hacker
Alex Lion
David Beazley
In [128]:
lines1 = [[l,l,l] for l in lines]
In [129]:
lines1
Out[129]:
[['one', 'one', 'one'],
 ['two', 'two', 'two'],
 ['three', 'three', 'three'],
 ['four', 'four', 'four'],
 ['five', 'five', 'five']]
In [130]:
list(enumerate(lines1))
Out[130]:
[(0, ['one', 'one', 'one']),
 (1, ['two', 'two', 'two']),
 (2, ['three', 'three', 'three']),
 (3, ['four', 'four', 'four']),
 (4, ['five', 'five', 'five'])]
In [131]:
ids = range(len(names))
In [132]:
for id_,n,s in zip(ids,names, surnames):
    print(id_, n, s)
0 Elsa Frozen
1 Elisa Hacker
2 Alex Lion
3 David Beazley
In [133]:
for id_,n in zip(ids,names, surnames):
    print(id_, n, s)
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-133-6b684d0225e9> in <module>()
----> 1 for id_,n in zip(ids,names, surnames):
      2     print(id_, n, s)

ValueError: too many values to unpack (expected 2)
In [134]:
for id_,n,s,a in zip(ids,names, surnames):
    print(id_, n, s)
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-134-fe13af890735> in <module>()
----> 1 for id_,n,s,a in zip(ids,names, surnames):
      2     print(id_, n, s)

ValueError: not enough values to unpack (expected 4, got 3)

problem

  • Write a function vector_add which adds elements from two lists item by item.
In [135]:
def vector_add(v1, v2):
    return sum(x+y for x,y in zip(v1, v2))
In [136]:
vector_add(range(10),range(10))
Out[136]:
90

problem

  • Implement quicksort which sorts list of numbers based on strategy of pivoting.
In [137]:
[1,23] + [23,45]
Out[137]:
[1, 23, 23, 45]
In [138]:
[1,2,3] + [3] + [4,5,6]
Out[138]:
[1, 2, 3, 3, 4, 5, 6]
In [139]:
[1,2,3] + [3]
Out[139]:
[1, 2, 3, 3]
In [140]:
def quick(items):
    if items==[]:
        return []
    
    p = items[0]
    less = [i for i in items[1:] if i<=p]
    more = [i for i in items[1:] if i>p]
    return quick(less) + [p] + quick(more)
    
In [141]:
quick([23,2,12,56,1,2,3,9,1,8,2])
Out[141]:
[1, 1, 2, 2, 2, 3, 8, 9, 12, 23, 56]

String formating

In [142]:
for i in range(1,11):
    print(i, i*i, i*i*i)
1 1 1
2 4 8
3 9 27
4 16 64
5 25 125
6 36 216
7 49 343
8 64 512
9 81 729
10 100 1000
In [143]:
for i in range(1,11):
    print(str(i).rjust(2), str(i*i).rjust(3), str(i*i*i).rjust(4))
 1   1    1
 2   4    8
 3   9   27
 4  16   64
 5  25  125
 6  36  216
 7  49  343
 8  64  512
 9  81  729
10 100 1000
In [144]:
"wizard of {}  is {}".format("oz", "python")
Out[144]:
'wizard of oz  is python'
In [145]:
"wizard of {1} is {0}".format("python","oz")
Out[145]:
'wizard of oz is python'
In [146]:
"wizard of {wiz} is in {place}".format(wiz="python", place="oz")
Out[146]:
'wizard of python is in oz'
In [147]:
for i in range(1,11):
    print("{num:2d} {sqr:3d} {cube:4d}".format(num=i,sqr=i*i,cube=i**3))
 1   1    1
 2   4    8
 3   9   27
 4  16   64
 5  25  125
 6  36  216
 7  49  343
 8  64  512
 9  81  729
10 100 1000

problem

  • Write a function pascal which generates pascal triangle as list of list as shon below. the triangle shown below should be generated as a list [[1],[1,1],[1,2,1]]
        1
      1   1
    1   2   1
  • Write a function to pretty print pascal triangle.
In [151]:
def pascal(base):
    t = [[1]]
    for i in range(base-1):
        prevbase = t[-1]
        pre = [0] + prevbase
        post = prevbase + [0]
        newbase = [x+y for x,y in zip(pre, post)]
        t.append(newbase)
        
    return t
In [150]:
def pascal_(base):
    t = [[1]]
    for i in range(base-1):
        prevbase = t[-1]
        baseln = len(prevbase)
        newbase = [1] + [prevbase[i]+prevbase[i+1] for i in range(baseln-1)] + [1]
        t.append(newbase)
    return t
In [152]:
pascal(5)
Out[152]:
[[1], [1, 1], [1, 2, 1], [1, 3, 3, 1], [1, 4, 6, 4, 1]]
In [153]:
pascal_(5)
Out[153]:
[[1], [1, 1], [1, 2, 1], [1, 3, 3, 1], [1, 4, 6, 4, 1]]
In [168]:
def print_pascal(t):
    def formatrow(row):
        s = ""
        for item in row:
            s = s + "{item:{maxdigits}d}".format(item=item, maxdigits=maxdigits+1)
        return s
    
    maxdigits = len(str(max(t[-1])))
    basesize = len(t[-1])
    maxwidth = basesize*maxdigits + basesize -1
    
    for row in t:
        strrow = formatrow(row)
        print(strrow.center(maxwidth))
In [169]:
print_pascal(pascal(16))
                                         1                                     
                                       1    1                                  
                                    1    2    1                                
                                  1    3    3    1                             
                               1    4    6    4    1                           
                             1    5   10   10    5    1                        
                          1    6   15   20   15    6    1                      
                        1    7   21   35   35   21    7    1                   
                     1    8   28   56   70   56   28    8    1                 
                   1    9   36   84  126  126   84   36    9    1              
                1   10   45  120  210  252  210  120   45   10    1            
              1   11   55  165  330  462  462  330  165   55   11    1         
           1   12   66  220  495  792  924  792  495  220   66   12    1       
         1   13   78  286  715 1287 1716 1716 1287  715  286   78   13    1    
      1   14   91  364 1001 2002 3003 3432 3003 2002 1001  364   91   14    1  
    1   15  105  455 1365 3003 5005 6435 6435 5005 3003 1365  455  105   15    1
In [170]:
%matplotlib inline
In [ ]:
 
In [171]:
import matplotlib.pyplot as plt
def imshow(img):
    plt.imshow(img,cmap=plt.cm.gray)
    plt.show()
In [172]:
imshow(t)
In [173]:
imshow(transpose(t))
In [174]:
imshow(rotate90clockwise(t))

Testing

In [178]:
%%file functions.py
def square(x):
    """
    >>> square(-1)
    1
    >>> square(1)
    1
    """
    return x*x


def sumofsquares(x,y):
    """
    >>> sumofsquares(2,3)
    13
    >>> sumofsquares(-1,-1)
    2
    """
    return square(x) + square(y)

def add(x,y):
    """
    >>> add(1,2)
    1
    """
    return x+y

    
Overwriting functions.py
In [179]:
!python -m doctest -v functions.py
Trying:
    add(1,2)
Expecting:
    1
**********************************************************************
File "/home/vikrant/trainings/2018/vmware-feb-python/functions.py", line 22, in functions.add
Failed example:
    add(1,2)
Expected:
    1
Got:
    3
Trying:
    square(-1)
Expecting:
    1
ok
Trying:
    square(1)
Expecting:
    1
ok
Trying:
    sumofsquares(2,3)
Expecting:
    13
ok
Trying:
    sumofsquares(-1,-1)
Expecting:
    2
ok
1 items had no tests:
    functions
2 items passed all tests:
   2 tests in functions.square
   2 tests in functions.sumofsquares
**********************************************************************
1 items had failures:
   1 of   1 in functions.add
5 tests in 4 items.
4 passed and 1 failed.
***Test Failed*** 1 failures.
In [189]:
%%file functions.py
def square(x):
    """
    >>> square(-1)
    1
    >>> square(1)
    1
    """
    return x*x


def sumofsquares(x,y):
    """
    >>> sumofsquares(2,3)
    13
    >>> sumofsquares(-1,-1)
    2
    """
    return square(x) + square(y)

def add(x,y):
    """
    >>> add(1,2)
    1
    """
    return x+y

def test_square():
    assert square(-1) == 1
    assert square(2)== 4
    assert square(4) == 15
    
def test_sumofsquares():
    assert sumofsquares(2,3)==13
    assert sumofsquares(-1,-1)==2
     
def hello_test():
    assert 1 == 2
    
def test123():
    assert 2==3
    
def testsum():
    print(sum(range(10)))
Overwriting functions.py
In [190]:
!py.test -v functions.py
============================= test session starts ==============================
platform linux -- Python 3.6.1, pytest-3.0.7, py-1.4.33, pluggy-0.4.0 -- /home/vikrant/usr/local/anaconda3/bin/python
cachedir: .cache
rootdir: /home/vikrant/trainings/2018/vmware-feb-python, inifile:
collected 4 items 

functions.py::test_square FAILED
functions.py::test_sumofsquares PASSED
functions.py::test123 FAILED
functions.py::testsum PASSED

=================================== FAILURES ===================================
_________________________________ test_square __________________________________

    def test_square():
        assert square(-1) == 1
        assert square(2)== 4
>       assert square(4) == 15
E       assert 16 == 15
E        +  where 16 = square(4)

functions.py:30: AssertionError
___________________________________ test123 ____________________________________

    def test123():
>       assert 2==3
E       assert 2 == 3

functions.py:40: AssertionError
====================== 2 failed, 2 passed in 0.06 seconds ======================

To install pytest use following command

pip3 install pytest

Working with files

In [191]:
import this
The Zen of Python, by Tim Peters

Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!
In [192]:
%%file data.txt
The Zen of Python, by Tim Peters

Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!
Writing data.txt
In [193]:
f = open("data.txt")
In [194]:
f.read()
Out[194]:
"The Zen of Python, by Tim Peters\n\nBeautiful is better than ugly.\nExplicit is better than implicit.\nSimple is better than complex.\nComplex is better than complicated.\nFlat is better than nested.\nSparse is better than dense.\nReadability counts.\nSpecial cases aren't special enough to break the rules.\nAlthough practicality beats purity.\nErrors should never pass silently.\nUnless explicitly silenced.\nIn the face of ambiguity, refuse the temptation to guess.\nThere should be one-- and preferably only one --obvious way to do it.\nAlthough that way may not be obvious at first unless you're Dutch.\nNow is better than never.\nAlthough never is often better than *right* now.\nIf the implementation is hard to explain, it's a bad idea.\nIf the implementation is easy to explain, it may be a good idea.\nNamespaces are one honking great idea -- let's do more of those!"
In [195]:
f.read()
Out[195]:
''
In [196]:
f.close()
In [197]:
f = open("data.txt")
In [198]:
f.readline()
Out[198]:
'The Zen of Python, by Tim Peters\n'
In [199]:
f.readline()
Out[199]:
'\n'
In [200]:
f.readline()
Out[200]:
'Beautiful is better than ugly.\n'
In [202]:
f = open("data.txt")
line = f.readline()
while line:
    print(line, end="")
    line = f.readline()
The Zen of Python, by Tim Peters

Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!
In [203]:
f = open("data.txt")
In [204]:
lines = f.readlines()
In [205]:
lines
Out[205]:
['The Zen of Python, by Tim Peters\n',
 '\n',
 'Beautiful is better than ugly.\n',
 'Explicit is better than implicit.\n',
 'Simple is better than complex.\n',
 'Complex is better than complicated.\n',
 'Flat is better than nested.\n',
 'Sparse is better than dense.\n',
 'Readability counts.\n',
 "Special cases aren't special enough to break the rules.\n",
 'Although practicality beats purity.\n',
 'Errors should never pass silently.\n',
 'Unless explicitly silenced.\n',
 'In the face of ambiguity, refuse the temptation to guess.\n',
 'There should be one-- and preferably only one --obvious way to do it.\n',
 "Although that way may not be obvious at first unless you're Dutch.\n",
 'Now is better than never.\n',
 'Although never is often better than *right* now.\n',
 "If the implementation is hard to explain, it's a bad idea.\n",
 'If the implementation is easy to explain, it may be a good idea.\n',
 "Namespaces are one honking great idea -- let's do more of those!"]
In [206]:
for line in open("data.txt"):
    print(line, end="")
The Zen of Python, by Tim Peters

Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!
In [207]:
list(open("data.txt"))
Out[207]:
['The Zen of Python, by Tim Peters\n',
 '\n',
 'Beautiful is better than ugly.\n',
 'Explicit is better than implicit.\n',
 'Simple is better than complex.\n',
 'Complex is better than complicated.\n',
 'Flat is better than nested.\n',
 'Sparse is better than dense.\n',
 'Readability counts.\n',
 "Special cases aren't special enough to break the rules.\n",
 'Although practicality beats purity.\n',
 'Errors should never pass silently.\n',
 'Unless explicitly silenced.\n',
 'In the face of ambiguity, refuse the temptation to guess.\n',
 'There should be one-- and preferably only one --obvious way to do it.\n',
 "Although that way may not be obvious at first unless you're Dutch.\n",
 'Now is better than never.\n',
 'Although never is often better than *right* now.\n',
 "If the implementation is hard to explain, it's a bad idea.\n",
 'If the implementation is easy to explain, it may be a good idea.\n',
 "Namespaces are one honking great idea -- let's do more of those!"]
In [ ]: