Apr 15-18, 2019 Vikrant Patil
These notes are available online at http://notes.pipal.in/2019/arcesium_basic_apr/day3.html
© Pipal Academy LLP
We will be using python 3 (>= 3.0) from anaconda for this training. You can download it from
def circlearea(radius=1.0): #default paramenter.
return 3.14*radius*radius
circlearea() # radius is taken as 1.0 as default value
print(1)
print(2) # end = new line
print(1, end=",")
print(2, end=",")
problems
write a function minumum2 to minimum of two number.
>>> minimum2(2,3)
2
write a function minimum3 to find minimum from three numbers
>>> minimum3(3,1,5)
1
if 2 > 3:
print(2)
else:
print(3)
2 > 4
2 <= 4
2 >= 4
2 == 3
def min2(x, y):
if x < y:
return x
else:
return y
min2(5, 6)
def min3(x, y, z):
return min2( min2(x, y), z)
def min3(x, y, z):
if x < y and x <z:
return x
elif y < x and y < z:
return y
else:
return z
primes = [2, 3, 5, 7, 11, 13, 17, 19]
for p in primes:
print(p, p*p)
for p in primes:
print(str(p).rjust(2), str(p*p).rjust(3))
for c in "This string with some text in it":
print(c, end=",")
for item in (1, 2, 3, 4, 5, 6):
print(item, end=" ")
help(print)
print(1, 2, 3)
print(1, 2, 3, sep="_")
%%file ls.py
import sys, os
def ls(dirname=None):
if dirname is None:
dirname = os.getcwd()
files = os.listdir(dirname)
for file in files:
print(file)
def main():
if len(sys.argv)>1:
ls(sys.argv[1])
else:
ls()
if __name__ == "__main__":
print("*"*5, sys.argv)
main()
!python ls.py
from ls import ls
ls()
ls("/home")
!python ls.py /home/vikrant/trainings/
primes
def square(x):
return x*x
s = []
for p in primes:
s.append(square(p))
print(s)
[p*p for p in primes]
for i in range(7):
print(primes[i]*primes[i], end=",")
len(primes)
[p*p*p for p in primes]
[n*n for n in range(20) if n%2==0]
[n*n for n in range(20) if n%2==0]
[1, 2, 3, 4]
col1 = [1,1,1]
col2 = [2, 2, 2]
col3 = [3, 3, 3]
table = [col1, col2, col3]
table
tables = [[n*i for i in range(1, 11)] for n in range(1, 6)]
tables
def evens(seq):
return [e for e in seq if e%2==0]
evens([1, 23,2, 3,5, 45, 66, 87])
def factors(n):
return [f for f in range(1, n+1) if n%f==0]
factors(5)
factors(6)
factors(7)
factors(9)
factors(10)
def is_prime(p):
return factors(p)==[1,p]
is_prime(5)
is_prime(10)
def primes(n):
return [p for p in range(1, n+1) if is_prime(p)]
primes(50)
problems
[i for i in range(1, 51)]
[i for i in range(1, 100) if i%7==0]
sum([i for i in range(1000) if i%7==0 or i%11==0])
for p in primes(20):
print(p)
primes_ = primes(20)
for p in primes_:
print(p)
for p in reversed(primes_):
print(p)
rp = reversed(primes_) #rp is not a list, it is iterator in rversed way to original list, to be used only once
for p in rp:
print(p)
for p in rp:
print(p)
[p for p in reversed(primes_)] # new copy in reversed way
primes_[::-1] # new copy in reversed way
primes_
primes_.reverse() # this changes original data, it is not copy
primes_
import this
poem = """
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!
"""
lines = poem.split("\n")
lines
for i, line in enumerate(lines): # enumerate iterates with two items , index and the object from seq
print(i, line)
x, y = 2, 3
for i, line in enumerate(lines): # enumerate iterates with two items , index and the object from seq
print(i+1, line)
first = ["Elisa", "Elsa", "Alice"]
second = ["Hacker", "Frozen", "Wonder"]
zip interates over more than one sequences at a time giving one item from each sequence.
for x,y in zip(first, second):
print(x, y)
first = ["Elisa", "Elsa", "Alice"]
second = ["Hacker", "Frozen", "Wonder"]
third = ["A", "B", "C", "D"]
for x, y, z in zip(first, second, third):
print(x, y, z)
for x, y, z in zip(first, second, third[1:]):
print(x, y, z)
%%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!
with open("data.txt") as f:
print(f.read())
f = open("data.txt")
f.read()
f.close()
with open("data.txt") as data:
for line in data:
print(line, end="") # because line contains its own new line
with open("data.txt") as data:
print(data.readline(), end="")
print(data.readline(), end="")
print(data.readline(), end="")
print(data.readline(), end="")
range(5)
for i in range(5):
print(i)
f = open("data.txt")
f
[l.strip() for l in f]
f.close()
f = open("data.txt")
lines = f.readlines()
f.close()
lines
lets build unix utilities cat, head, wc
%%file cat.py
import sys
def cat(filename):
with open(filename) as f:
print(f.read())
if __name__ == "__main__":
cat(sys.argv[1])
!python cat.py data.txt
print(range(5))
r = range(5)
r[0]
%%file head.py
import sys
def head(filename, n):
with open(filename) as f:
for i in range(n):
print(f.readline(), end="")
if __name__ == "__main__":
head(sys.argv[1], int(sys.argv[2]))
!python head.py data.txt 5
%%file wc.py
import sys
def charcount(file):
with open(file) as f:
return len(f.read())
def linecount(file):
with open(file) as f:
return len(f.readlines())
def wordcount(file):
with open(file) as f:
return len(f.read().split())
if __name__ == "__main__":
f = sys.argv[1]
print(linecount(f), wordcount(f), charcount(f), f)
!python wc.py data.txt
with open("numbers.txt", "w") as f: # r (read) , w (write), a (append)
nums = [1, 2, 3, 4]
words = ["one", "two", "three", "four"]
for n, w in zip(nums, words):
f.write(str(n) + " " + w) # as this is text mode, you can write only string i.e. text!
f.write("\n")
!python cat.py numbers.txt
with open("numbers.txt", "a") as f: # a (append)
nums = [1, 2, 3, 4]
words = ["one", "two", "three", "four"]
for n, w in zip(nums, words):
f.write(str(n) + " " + w) # as this is text mode, you can write only string i.e. text!
f.write("\n")
!python cat.py numbers.txt
tables
def writeCSV(data, filename):
with open(filename, "w") as f:
for row in data:
textrow = ",".join(map(str, row))
f.write(textrow + "\n")
writeCSV(tables, "tables.csv")
!python cat.py tables.csv
f = open("data.txt", "w")
help(f.writelines)
f.writelines(["a","b","c"])
f.close()
!python cat.py data.txt
def csvparser(csvfile):
with open(csvfile) as f:
d = []
for line in f:
d.append(line.strip().split())
return d
csvparser("tables.csv")
def csvparser(csvfile):
def to_int(items):
return list(map(int, items))
with open(csvfile) as f:
return [to_int(line.strip().split(",")) for line in f]
csvparser("tables.csv")
stock = {
"name":"Infosys",
"value": 1001,
"exchange":"BSE",
"gain":5.5
}
stock['name']
stock.get("name")
stock.get("date")
stock['date']
stock.get("date", "17 Apr 19")
stock
del stock['name']
stock
stock['name'] = "Infosys"
stock
%%file inputs.txt
param1 45
maxgain 5
startyear 2018
month March
def parseinputs(filename):
with open(filename) as f:
inputs = {}
for line in f:
key, value = line.strip().split()
inputs[key] = value
return inputs
parseinputs("inputs.txt")
{i:i for i in range(5)}
inputs = parseinputs("inputs.txt")
inputs
for item in inputs:
print(item)
for k,v in inputs.items():
print(k , v)
for v in inputs.values():
print(v)
list("hello")
dict([("a",1), ("b",2), ("c",3)])
dict(zip(first, second))
{1, 2, 2} # set
{"a":1, "b":2} # dictionary
%%file words.txt
one
one two
one two three
one two three four
one two three four five
one two three four six
one two three seven six
one two eight seven six
one nine eight seven six
ten nine eight seven
ten nine eight
ten nine
ten
words = ["one", "one", "two", "three", "three", "three"]
words.count("one")
uniquewords = set(words)
uniquewords
for w in uniquewords:
print(w, words.count(w))
freq = {}
for w in words:
if w in freq:
freq[w] += 1
else:
freq[w] = 1
freq
freq = {}
for w in words:
freq[w] = freq.get(w, 0) + 1
freq
def get_words(filename):
with open(filename) as f:
return f.read().split()
def wordfreq(words):
freq = {}
for w in words:
freq[w] = freq.get(w, 0) + 1
return freq
words = get_words("words.txt")
freq = wordfreq(words)
freq
for w, f in freq.items():
print(w.rjust(7), f)
def get_freq(r):
return r[1]
for w, f in sorted(freq.items(), key=get_freq):
print(w.rjust(7), f)
for w, f in sorted(freq.items(), key=get_freq):
print(w.rjust(7), f*"*")
%%file bank.py
balance = 0
def get_balance():
return balance
def deposit(amount):
global balance
balance += amount
def withdraw(amount):
global balance
balance -= amount
import bank
bank.get_balance()
bank.deposit(100)
bank.get_balance()
%%file bank1.py
def make_account():
return {"balance":0}
def get_balance(account):
return account['balance']
def deposit(account, amount):
account['balance'] += amount
def withdraw(account, amount):
account['balance'] -= amount
import bank1
a1 = bank1.make_account()
a2 = bank1.make_account()
bank1.deposit(a1, 100)
bank1.deposit(a2, 1000)
bank1.get_balance(a1)
bank1.get_balance(a2)
class BankAccount:
def __init__(self):
self.balance = 0
def get_balance(self):
return self.balance
def deposit(self, amount):
self.balance += amount
def withdraw(self, amount):
self.balance -= amount
a3 = BankAccount()
a4 = BankAccount()
type(a3)
type(a4)
a3.get_balance()
a3.deposit(200)
a3.get_balance()
a3.withdraw(20)
a3.get_balance()
class BankAccount:
def __init__(self, name):
self.balance = 0
self.name = name
def get_balance(self):
return self.balance
def deposit(self, amount):
self.balance += amount
def withdraw(self, amount):
self.balance -= amount
def get_name(self):
return self.name
a5 = BankAccount("Python")
a5.get_balance()
a5.get_name()