Nov 26-30, 2018 Vikrant Patil
These notes are available online at http://notes.pipal.in/2018/arcesium-basic-nov/day2.html
© Pipal Academy LLP
Day 1 | Day 2 | Day 3 | Day 4 | Day 5
We will be using python 3 (>= 3.0) from anaconda for this training. You can download it from
len_ = len(range(10))
len = 5 # don't use builtins as variable names
len([1,2,3])
del len
len([1,2,3])
name = "Alice"
name.upper()
name.lower()
name.split("i")
name_ = " Alice "
name_.strip() # it removes only trailing spaces
fullname = "Alice in wonderland "
fullname.strip()
def functionname(paramater):
upper = paramater.upper()
return upper
functionname("hello")
functionname(2)
functionname("2")
problem Given any text write a function to
>>> wordcount(poem)
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!
"""
'''
this
is
multiline string
'''
"""
one
two
three four
"""
def linecount(text):
lines = text.split("\n")
return len(lines)
def wordcount(text):
words = text.split()
return len(words)
def charcount(text):
return len(text)
linecount(poem)
wordcount(poem)
charcount(poem)
text = "word1 word2 word3"
text.count(" ") + 1
text = "word1 word2 word3"
text.count(" ") + 1
s = "hello\tworld"
print(s)
s.count(" ")
s.count("\t")
numbers = [1,1,1,1, 2,2, 3, 3, 3, 4, 4, 5]
numbers.count(1)
numbers.count(5)
numbers.append(6)
numbers
numbers.insert(0, -1)
numbers
numbers.extend(range(6,10))
numbers
numbers.extend([6,13,17.19])
numbers
numbers.insert(2, 100)
numbers
sorted(numbers)
sorted(numbers, reverse=True)
numbers.append("a")
sorted(numbers)
numbers.pop()
numbers
sorted(numbers)
words = ["one", "two", "three", "four", "five"]
sorted(words)
sorted(words, reverse=True)
numbers.remove(-1)
numbers
numbers.remove(6)
numbers
help(numbers.pop)
help(numbers)
numbers[0]
numbers[2:6] # start at 2nd index till 6th (excluding)
numbers[2:8:2] # start at 2nd index till 8th (exclude) at interval of 2
numbers[2:]
digits = list(range(10))
digits
digits[2:] # drop frist two
digits[:5] #take first five
digits[:]
def head(n, seq):
return seq[:n]
head(3, digits)
digits[::-1] #reverse
poem[0]
poem[:50]
t = (1, 2, 3, 4, 5)
t.count(1)
t.index(3)
t[:2]
d = {"one":1,
"two":2,
"three":3,
"four":4
}
d
d.keys()
d.values()
"one" in d
1 in d
1 in d.values()
numbers
first = numbers.index(1)
first
def secondindex(seq, item):
first = seq.index(item)
tail = seq[first+1:]
second = tail.index(item)
return first + second + 1
secondindex(numbers, 2)
numbers.index(2)
d['one']
d.get("one")
d.get("five")
d.get("five", "Item not Found")
if "hel" in "hello":
print("hel is with hello")
print("That means this conditon is true!")
else:
print("That means hel is not in hello!")
cond1, cond2, cond3, cond4 = [True]*4
if cond1:
print("cond1")
elif cond2:
print("cond2")
elif cond3:
print("cond3")
elif cond4:
print("cond4")
else:
print("else")
cond1, cond2, cond3, cond4 = False, False, True, True
if cond1:
print("cond1")
elif cond2:
print("cond2")
elif cond3:
print("cond3")
elif cond4:
print("cond4")
else:
print("else")
[1]*5
cond1, cond2, cond3, cond4 = False, False, False, False
if cond1:
print("cond1")
elif cond2:
print("cond2")
elif cond3:
print("cond3")
elif cond4:
print("cond4")
else:
print("else")
problem
ext type
exe executable
py python
xlsx excel
doc document
else unknown
def filetype(filename):
if filename.endswith(".exe"):
return "executable"
elif filename.endswith(".py"):
return "python"
elif filename.endswith(".xlsx"):
return "excel"
elif filename.endswith("doc"):
return "document"
else:
return "unknown"
filetype("hello.py")
filetype("anaconda.exe")
filetype("system.dll")
f = "virtuenv.exe"
filetype(f)
def add(x, y):
return x+y
a = 3
b = 15
add(a, b)
add(15, 20)
filetype("windows.exe")
def findextn(filename):
return filename.split(".")[-1]
def filetype_(filename):
data = {"exe": "executable",
"py" : "python",
"xlsx": "excel",
"doc": "document"}
extn = findextn(filename)
return data.get(extn, "unknown")
filetype_("hello.py")
import math
math.pi
def cylinder_volume(radius, height):
return math.pi*radius**2*height
cylinder_volume(1, 1)
from math import pi
pi
import math as pymath
pymath.sin(pymath.pi)
from math import pi as pie
pie
from pymath import pi
pymath.pi
import os
del pymath
pymath
import os
os.getcwd() #current working directory
os.listdir() # list of all items from current directory
help(os.getcwd)
os.listdir("/home/vikrant/trainings/2018")
training_dirs = os.listdir("/home/vikrant/trainings/2018")
training_dirs
os.mkdir("test")
os.path.exists("test")
os.path.isdir("test")
os.path.isfile("test")
os.path.getsize("day1.html")
dirpath = os.getcwd()
os.path.join(dirpath, "day1.html")
words
" ".join(words)
"_".join(words)
"/".join(words)
setence = 'one two three four five'
w = setence.split()
w
" ".join(w)
w
sent = " ".join(w)
sent
w
problem
countfiles to count files from given directory (include directories as well)import os
def countfiles(dirpath):
contents = os.listdir(dirpath)
return len(contents)
countfiles(".")
countfiles("/home/vikrant/")
%%file wc.py
"""
A module for counting number of lines, words and charecters from given text
"""
def wordcount(text):
"""
Counts words from given text
"""
return len(text.split())
def linecount(text):
return len(text.split("\n"))
def charcount(text):
return len(text)
import wc
wc.wordcount(poem)
help(wc)
os.getcwd()
import hello
hello.greeting()
os.getcwd()
def foo(x):
print("foo:", x)
foo
foo(4)
%%file square.py
def square(x):
return x*x
print(square(3))
!python square.py
%%file square1.py
import sys
def square(x):
return x*x
print(sys.argv)
a = float(sys.argv[1])
print(square(a))
!python square1.py 5 543 hello xyz hsjdh jshdjh
with open("poem.txt") as f:
print(f.read())
%%file wc.py
"""
A module for counting number of lines, words and charecters from given text
"""
import sys
def wordcount(text):
"""
Counts words from given text
"""
return len(text.split())
def linecount(text):
return len(text.split("\n"))
def charcount(text):
return len(text)
filename = sys.argv[1]
with open(filename) as f:
text = f.read()
print(linecount(text), wordcount(text), charcount(text), filename)
!python wc.py poem.txt
problem
%%file add.py
import sys
def add():