words = "For today’s practice make use of notebook module1-day4.ipynb created in your enviroment.".split()9 Module 1 - Day 4
Topics
- Conditions
- Python modules - some built in modules os, sys
- Writing your own modules
- Distinguishing modules and scripts
For today’s practice make use of notebook module1-day4.ipynb created in your enviroment. Shut down kernel for all previous notebooks by right cliking on notbeook on left hand side file browser.
9.1 Quick recap of for loop
words['For',
'today’s',
'practice',
'make',
'use',
'of',
'notebook',
'module1-day4.ipynb',
'created',
'in',
'your',
'enviroment.']
for w in words:
print("X" + w)XFor
Xtoday’s
Xpractice
Xmake
Xuse
Xof
Xnotebook
Xmodule1-day4.ipynb
Xcreated
Xin
Xyour
Xenviroment.
for x in [1, 2, 3, 4, 5]:
print(x*x)1
4
9
16
25
stocks = [{"name":"AAPLE", "value":245},
{"name":"AT&T", "value":300},
{"name": "TESLA", "value": 200}]values = []
for s in stocks:
values.append(s['value'])values[245, 300, 200]
def extract_values(stockslist):
values = []
for s in stocks:
values.append(s['value'])
return valuesextract_values(stocks)[245, 300, 200]
def extract_items(stocks, itemname):
values = []
for s in stocks:
values.append(s[itemname])
return valuesextract_items(stocks, "name")['AAPLE', 'AT&T', 'TESLA']
extract_items(stocks, "value")[245, 300, 200]
def mysum(numbers):
s = 0
for i in numbers:
s = s + i
return smysum([245, 300, 200])745
- Write a function product which finds product of all elements from a list.
>>> product([3, 2, 4])
24
- Write a function factorial to find factorial of a number. Hint : Use function range(1,n) to generate numbers from 1 to n. if you put for loop on this range(1,n) it will give numbers 1 to n
>>> factorial(5)
120
- Write a function findlens which finds lengths of every word from a given list of words.
>>> findlens(["one", "two", "three"])
[3, 3, 5]
def product(numbers):
p = 1
for n in numbers:
p = p * n
return pdef factorial(n):
return product(range(1, n+1))factorial(5)120
for i in range(1, 5):
print(i)1
2
3
4
for i in range(10):
print(i)0
1
2
3
4
5
6
7
8
9
for i in range(1, 11):
print(i)1
2
3
4
5
6
7
8
9
10
def foo(x): # this is definition
return x*xfoo(5)25
factorial(5)120
factorial(5)120
def findlens(words):
lenghts = []
for w in words:
lenghts.append(len(w))
return lenghtsfindlens(words)[3, 7, 8, 4, 3, 2, 8, 18, 7, 2, 4, 11]
words['For',
'today’s',
'practice',
'make',
'use',
'of',
'notebook',
'module1-day4.ipynb',
'created',
'in',
'your',
'enviroment.']
9.2 conditons
- if some conditon is satisfied do something….
if cond:
do something
- only one the if/elif/else conditions will be executed
if cond1:
do 1
elif cond2:
do 2
elif cond3:
do 3
else:
do otherwise
- only one of the if/else condition will be executed
if cond:
do something
else:
do rest
text = "this is test"text.startswith("this")True
x = 6
y = 10x > yFalse
x < yTrue
x == yFalse
x != y # not equalTrue
x <= yTrue
x >= yFalse
(x > y) and (text.startswith("t"))False
x > y and text.startswith("t")False
"this" in textTrue
words['For',
'today’s',
'practice',
'make',
'use',
'of',
'notebook',
'module1-day4.ipynb',
'created',
'in',
'your',
'enviroment.']
"For" in wordsTrue
"for" in words # case sensitiveFalse
def mymax(x, y):
if x> y:
return x
else:
return ymymax(45, 56)56
if x < y:
print("Y")
else:
print("X")Y
problems
- Write a function
find_words_of_lento find words of given length from given list.
>>> find_words_of_len(words, 3)
['one', 'two', 'six']
ones = [1, 1, 1, 1]x = ones.append(1)print(x)None
y10
print(x)None
xprint(x)None
def foo():
return Nonefoo()primes[] # this means primes already exists and I am about to access items from it
primes = [] # i am defining a new variable def find_words_of_len(words, length):
desired_words = []
for w in words:
if len(w) == length:
#return w this return here will stop the for loop the moment first word is found!
desired_words.append(w) #
#return desired_words # this will return a list with first word in a list
#return desired_words desired_words # this will return a list with first word in a list
return desired_words # look at the indentation!find_words_of_len(words, 4)['make', 'your']
words['For',
'today’s',
'practice',
'make',
'use',
'of',
'notebook',
'module1-day4.ipynb',
'created',
'in',
'your',
'enviroment.']
def find_words_of_len(words,x):
p=[]
for w in words:
if len(w)==x:
p.append(w)
return pfind_words_of_len(words, 4)['make', 'your']
sqrs_even = []
for i in range(20):
if i%2==0:
sqrs_even.append(i)sqrs_even[0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
def squares_even(numbers):
sqrs_even = []
for i in numbers:
if i%2==0:
sqrs_even.append(i)
return sqrs_evensquares_even(range(20))[0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
Write a function unique which will remove duplicates from a list.
>>> unique([1, 1, 2, 3, 1, 2, 3, 2, 4])
[1, 2, 3, 4]
def unique(items):
unique_box = []
for item in items:
if item not in unique_box:
unique_box.append(item)
return unique_boxunique([1, 2, 3, 1, 1, 12, 2, 3, 4, 7, 4, 7, 7])[1, 2, 3, 12, 4, 7]
def unique(items):
unique_box = []
for item in items:
if item in unique_box:
continue # continue statement allows to go back to for loop next iteration
else:
unique_box.append(item)
return unique_box9.3 modules
math--------------------------------------------------------------------------- NameError Traceback (most recent call last) Cell In[82], line 1 ----> 1 math NameError: name 'math' is not defined
import mathmath<module 'math' from '/opt/tljh/user/lib/python3.12/lib-dynload/math.cpython-312-x86_64-linux-gnu.so'>
math.sin(math.pi)1.2246467991473532e-16
math.exp(10)22026.465794806718
import randomrandom.random() # generate a random number betweeb 0 to 10.18358511958951218
random.choice(words) # this choosed a random item from a list'of'
random.choice(words)'module1-day4.ipynb'
words['For',
'today’s',
'practice',
'make',
'use',
'of',
'notebook',
'module1-day4.ipynb',
'created',
'in',
'your',
'enviroment.']
random.choice([1, 34,4 , 6, 2, 6])6
import math as m # you can give alias to the imported modulem.pi3.141592653589793
math.pi3.141592653589793
import osos.listdir() # this will give list of all files in current working directory['index.qmd',
'.ipynb_checkpoints',
'module1-day4.ipynb',
'module1-day1.ipynb',
'module1-day3.ipynb',
'module1-day2.ipynb']
os.getcwd()'/opt/arcesium-finop-25/website/live-notes'
"/home/jupyter-anmol/"os.listdir("/home/jupyter-vikrant/training/") # if you pass a folder name here ..
# it will give files and folders in that folder['README.md',
'pipalhub-magic',
'files',
'setup-anand.md',
'etc',
'users.txt',
'vendor',
'problems',
'quarto-1.8.26-linux-amd64.deb',
'final',
'website',
'requirements.txt',
'.git',
'.gitmodules',
'scripts',
'.gitignore',
'instructions.md']
files = os.listdir(os.getcwd())for f in files:
print(f, os.path.isfile(f))index.qmd True
.ipynb_checkpoints False
module1-day4.ipynb True
module1-day1.ipynb True
module1-day3.ipynb True
module1-day2.ipynb True
for f in files:
print(f, os.path.isfile(f))index.qmd True
.ipynb_checkpoints False
module1-day4.ipynb True
module1-day1.ipynb True
module1-day3.ipynb True
module1-day2.ipynb True
os.getcwd()'/opt/arcesium-finop-25/website/live-notes'
files = os.listdir('/opt/arcesium-finop-25/website/live-notes')for f in files:
if os.path.isfile(f):
print("f", f)
else:
print("d", f)f index.qmd
d test
d test1
d .ipynb_checkpoints
f module1-day4.ipynb
f module1-day1.ipynb
f module1-day3.ipynb
f module1-day2.ipynb
os.path.getsize("module1-day1.ipynb") # size in bytes75255
os.listdir("c:\\")--------------------------------------------------------------------------- FileNotFoundError Traceback (most recent call last) Cell In[114], line 1 ----> 1 os.listdir("c:\\") FileNotFoundError: [Errno 2] No such file or directory: 'c:\\'
os.path.sep'/'
os.path.join("c:", "Program Files")'c:/Program Files'
os.getcwd() # path to current working directory'/opt/arcesium-finop-25/website/live-notes'
os.listdir() # list files ['index.qmd',
'txt1.txt',
'test',
'test1',
'.ipynb_checkpoints',
'module1-day4.ipynb',
'module1-day1.ipynb',
'module1-day3.ipynb',
'module1-day2.ipynb',
'hello.txt']
os.path.getsize("hello.txt")0
os.path.getsize("untitled.txt")--------------------------------------------------------------------------- FileNotFoundError Traceback (most recent call last) Cell In[121], line 1 ----> 1 os.path.getsize("untitled.txt") File <frozen genericpath>:62, in getsize(filename) FileNotFoundError: [Errno 2] No such file or directory: 'untitled.txt'
os.path.getsize(os.path.join("test","untitled.txt"))86
relative_path = os.path.join("test","untitled.txt")relative_path'test/untitled.txt'
os.path.abspath(relative_path)'/opt/arcesium-finop-25/website/live-notes/test/untitled.txt'
problem - Write a function findpyfiles from given folder
findpyfiles("test")
['untitled.py', "untitled1.py", "untitled2.py", "untitled3.py", "untitled4.py"]
- How will you find biggest file from given list of files? hint: remember max with key argument?
- Write a function
greetingwhich greets randomly in variaus ways::
>>> greeting("Vikrant")
"Hello Vikrant"
>>> greeting("Vikrant")
"Namaste Vikrant"
>>> greeting("Vikrant")
"Good day Vikrant"
>>> greeting("Vikrant")
"Guten morgen Vikrant"
foldername = "test"hello--------------------------------------------------------------------------- NameError Traceback (most recent call last) Cell In[128], line 1 ----> 1 hello NameError: name 'hello' is not defined
"hello"'hello'
def is_pyfile(filename):
return filename.endswith(".py")is_pyfile("hello.py")True
is_pyfile("hello.txt")False
os.path.isfile("hello.txt")True
os.path.isfile("untitled.txt")False
os.path.isfile(os.path.join("test", "untitled.txt"))True
os.path.join("test", "untitled.txt")'test/untitled.txt'
os.listdir("test")['untitled1.py',
'.ipynb_checkpoints',
'untitled2.txt',
'untitled3.txt',
'untitled2.py',
'untitled3.py',
'untitled.py',
'untitled1.txt',
'untitled4.py',
'untitled.txt']
os.listdir("test")['untitled1.py',
'.ipynb_checkpoints',
'untitled2.txt',
'untitled3.txt',
'untitled2.py',
'untitled3.py',
'untitled.py',
'untitled1.txt',
'untitled4.py',
'untitled.txt']
import random
def greetings(name):
greets = ["Hello", "Namaskar", "Good day", "Have a nice day"]
greeting_for_now = random.choice(greets)
print(greeting_for_now, name)greetings("vikrant")Namaskar vikrant
def findpyfiles(folder):
files = os.listdir(folder)
pyfiles = []
for f in files:
if f.endswith(".py"):
pyfiles.append(f)
return pyfilesfindpyfiles("test")['untitled1.py', 'untitled2.py', 'untitled3.py', 'untitled.py', 'untitled4.py']
findpyfiles(os.getcwd())['untitled.py']
words['For',
'today’s',
'practice',
'make',
'use',
'of',
'notebook',
'module1-day4.ipynb',
'created',
'in',
'your',
'enviroment.']
max(words, key=len)'module1-day4.ipynb'
os.path.getsize("module1-day1.ipynb")75255
files = os.listdir(os.getcwd())files['index.qmd',
'txt1.txt',
'test',
'test1',
'.ipynb_checkpoints',
'module1-day4.ipynb',
'module1-day1.ipynb',
'module1-day3.ipynb',
'module1-day2.ipynb',
'hello.txt',
'untitled.py']
max(files, key=os.path.getsize)'module1-day2.ipynb'
for f in files:
print(f, os.path.getsize(f))index.qmd 185
txt1.txt 0
test 4096
test1 4096
.ipynb_checkpoints 4096
module1-day4.ipynb 55041
module1-day1.ipynb 75255
module1-day3.ipynb 63223
module1-day2.ipynb 79656
hello.txt 0
untitled.py 0
def find_biggest_file(folder):
files = os.listdir(folder)
filespaths = []
for f in files:
path = os.path.join(folder, f)
filespaths.append(path)
return max(filespaths, key=os.path.getsize)
os.path.getsize("untitled.txt")--------------------------------------------------------------------------- FileNotFoundError Traceback (most recent call last) Cell In[155], line 1 ----> 1 os.path.getsize("untitled.txt") File <frozen genericpath>:62, in getsize(filename) FileNotFoundError: [Errno 2] No such file or directory: 'untitled.txt'
find_biggest_file("test")'test/.ipynb_checkpoints'
find_biggest_file("test")'test/untitled.txt'
os.path.getsize("test") # it can estimate only file size not folder size4096
import datetimedate = datetime.datetime(2025, 11, 20)datedatetime.datetime(2025, 11, 20, 0, 0)
date1 = datetime.datetime(2025, 11, 25)date1 > dateTrue
date2 = datetime.datetime(2025, 11, 15)date2datetime.datetime(2025, 11, 15, 0, 0)
datedatetime.datetime(2025, 11, 20, 0, 0)
date2datetime.datetime(2025, 11, 15, 0, 0)
datedatetime.datetime(2025, 11, 20, 0, 0)
date2 < dateTrue
threedays = datetime.timedelta(days=3)date + threedaysdatetime.datetime(2025, 11, 23, 0, 0)
problem - Write a function trange which generates n dates from start date. if start is not given , today is taken as start date.
>>> trange(5, datetime.datetime(2019, 1, 1))
[datetime.datetime(2019, 1, 1, 0, 0),
datetime.datetime(2019, 1, 2, 0, 0),
datetime.datetime(2019, 1, 3, 0, 0),
datetime.datetime(2019, 1, 4, 0, 0),
datetime.datetime(2019, 1, 5, 0, 0)]
datetime.datetime.now() # this will give current date timedatetime.datetime(2025, 12, 15, 7, 56, 57, 352400)
def cylinder_volume(radius, height):
return math.pi*radius**2*height
cylinder_volume(1.0, 5)15.707963267948966
cylinder_volume(5, 1) # by mistake I passed arguments in wrong order78.53981633974483
cylinder_volume(radius=1, height=5) # named arguments15.707963267948966
cylinder_volume(height=5, radius=1)15.707963267948966
cylinder_volume(1, height=5)15.707963267948966
cylinder_volume(radius=1, 5)Cell In[209], line 1 cylinder_volume(radius=1, 5) ^ SyntaxError: positional argument follows keyword argument
def cylinder_volume(radius, height=1.0): # default argument value
return math.pi*radius**2*heightcylinder_volume(1) # this will take radius as 1 and helght 1 3.141592653589793
cylinder_volume(1, 5)15.707963267948966
cylinder_volume(radius=1, height=5) 15.707963267948966
def trange(n, startdate=None):
if startdate is None:
startdate = datetime.datetime.now()
dates = []
for i in range(n):
delta = datetime.timedelta(days=i)
dates.append(startdate + delta)
return datestrange(5)[datetime.datetime(2025, 12, 15, 8, 6, 53, 208864),
datetime.datetime(2025, 12, 16, 8, 6, 53, 208864),
datetime.datetime(2025, 12, 17, 8, 6, 53, 208864),
datetime.datetime(2025, 12, 18, 8, 6, 53, 208864),
datetime.datetime(2025, 12, 19, 8, 6, 53, 208864)]
trange(5, date)[datetime.datetime(2025, 11, 20, 0, 0),
datetime.datetime(2025, 11, 21, 0, 0),
datetime.datetime(2025, 11, 22, 0, 0),
datetime.datetime(2025, 11, 23, 0, 0),
datetime.datetime(2025, 11, 24, 0, 0)]