Module I - Day 4

Python Foundation

Nov-Jan 2025 batch, Vikrant Patil

Date: 26 Nov 2025

Click here for All Notes

login to https://traininghub.vikrant.dev/ with your username and create a notebook with name module1-day4.ipynb

© Vikrant Patil

loops

  • when we want to repeat some part of code
  • we want to some thing again and again till some condition is valid
  • we want to do something on every item from a collection
nums = [1, 2, 3, 5, 7, 11, 13]
for every_object in collection:
    do_some_operation(every_object)
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
Cell In[2], line 1
----> 1 for every_object in collection:
      2     do_some_operation(every_object)

NameError: name 'collection' is not defined
for n in nums:
    print(n)
1
2
3
5
7
11
13
for n in nums:
    print(n*n)
1
4
9
25
49
121
169

one major iteration pattern using for loop is to create a new collection using existing collection

nums -> squares of nums
nums -> absolute value of all numbers
words -> a new list of words where every word is uppper case
sqrs = []
for n in nums:
    sqr = n*n
    sqrs.append(sqr)
sqrs
[1, 4, 9, 25, 49, 121, 169]
words = ["one", "two", "three", "four", "five"]
caps_words= []
for w in words: # w is called as iteration variable .. it takes values from the collection one by one
    caps_words.append(w.upper())
print(caps_words) # look at the indentation. it means for loop is over
['ONE', 'TWO', 'THREE', 'FOUR', 'FIVE']
caps_words= []
for w in words: # w is called as iteration variable .. it takes values from the collection one by one
    caps_words.append(w.upper())
    print(caps_words) # look at the indentation. it means it is part of loop
['ONE']
['ONE', 'TWO']
['ONE', 'TWO', 'THREE']
['ONE', 'TWO', 'THREE', 'FOUR']
['ONE', 'TWO', 'THREE', 'FOUR', 'FIVE']
def fiboncci(n):
    if n<= 1:
        return 1
    else:
        return fiboncci(n-1) + fiboncci(n-2)
fiboncci(10)
89

for loop works on collection. - what if I want to put a loop that runs n times but I do not have collection - there is a way to create a dummy collection called range

range(10) # this will create numbers from 0 to 9
range(0, 10)
for i in range(10):
    print(i, end=",")
0,1,2,3,4,5,6,7,8,9,
for i in range(1, 11): # number from 1 to 10
    print(i, end=" ")
1 2 3 4 5 6 7 8 9 10 

problem - make use of fibonacci function to create a list that has first 10 fibonacci numbers.

[one, two, three, four, five]
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
Cell In[18], line 1
----> 1 [one, two, three, four, five]

NameError: name 'one' is not defined

one is taken as variable name

["one", "two", "three", "four", "five"]
['one', 'two', 'three', 'four', 'five']
words=["one","two","tree","four"]
caps_words=[]
for w in words:
    caps_words=caps_words.append(w.upper())
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
Cell In[20], line 4
      2 caps_words=[]
      3 for w in words:
----> 4     caps_words=caps_words.append(w.upper())

AttributeError: 'NoneType' object has no attribute 'append'
ones = [1, 1, 1]
ones.append(2) # there is response by interpreter! but it has appended
ones
[1, 1, 1, 2]
def foo():
    pass

def bar():
    return 1
foo()
bar()
1
x = foo()
y = bar()
print(x, y)
None 1
return_value = ones.append(2)
print(return_value)
None
words=["one","two","tree","four"]
caps_words=[]
for w in words:
    caps_words.append(w.upper())
caps_words
['ONE', 'TWO', 'TREE', 'FOUR']

make use of fibonacci function to create a list that has first 10 fibonacci numbers.

  • first 10 natural number - range(1, 11)
  • for i in range(1, 11): fibonacci(i)

bonus problem - Write a function product which will find product of numbers from given list

>>> product([1, 2, 3, 4])
24
sum([1, 2, 3, 4, 5, 7, 23])
45
def mysum(numbers):
    s = 0
    for n in numbers:
        s = s + n
    return s
    
1, 2, 3, 4, 5, 6
0 + 1 =>1
1 + 2 => 3
3 + 3 => 6
6 + 4 => 10
10 + 5 => 15
15 + 6 => 21
mysum([1, 2, 3, 4, 5, 6])
21

problem - write a function to compute factorial which computes factorial of given n

>>> factorial(5)
120
def product(numbers):
    p = 1
    for n in numbers:
        p = p * n
    return p
    
five = [1, 2, 3, 4, 5]
product(five)
120
six = [1, 2, 3, 4, 5, 6]
product(six)
720
def factorial(n):
    return product(range(1, n+1))
factorial(10)
3628800
factorial(5)
120

modules

random
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
Cell In[43], line 1
----> 1 random

NameError: name 'random' is not defined
import random
random
<module 'random' from '/usr/lib/python3.13/random.py'>
random.random()  # this is function which generates random number between 0 to 1
0.19248968668834499
random.choice(nums) # choose random item from given collection
5
import math
math.pi
3.141592653589793
math.e
2.718281828459045
math.sin(math.pi)
1.2246467991473532e-16
5**3
125
math.pow(5, 3)
125.0
import os
os.getcwd() # get current working directory/folder
'/home/vikrant/programming/work/github/vikrant.dev/python-foundation-professionals'
os.getenv("HOME") # gives environment variable
'/home/vikrant'
os.listdir("/home/vikrant/trainings/")
['2023',
 '2018',
 'nakul',
 'day5.org',
 '2022',
 'hello.py',
 'day5.org~',
 '2024',
 'selenium_code_for_team',
 '2020',
 'trainingvenv',
 '2021',
 '2019',
 '2025',
 '2017',
 'indexdata.xlsx',
 'selenium_venv']
os.listdir() # by default it will return files/folders from current working directory
['index.qmd',
 'topics.qmd~',
 'notes.qmd',
 '_quarto.yml',
 'notes.qmd~',
 'day4.org~',
 'push',
 'styles.css',
 'trainer.qmd',
 '.quarto',
 'index.qmd~',
 'day4.org',
 '_quarto.yml~',
 '_site',
 '.gitignore',
 'module1-day1.ipynb',
 'module1-day2.ipynb',
 'topics.qmd',
 'about.qmd',
 'module1-day3.ipynb',
 'Makefile~',
 'Makefile',
 '.ipynb_checkpoints',
 'module1-day4.ipynb']
os.path # is submodule in os module
<module 'posixpath' (frozen)>
os.path.isdir("/home/vikrant/trainings/")
True
os.path.isdir("/home/vikrant/trainings/day5.org")
False
os.path.isfile("/home/vikrant/trainings/day5.org")
True
os.path.getsize("module1-day1.ipynb")
50000
files = os.listdir()
files
['index.qmd',
 'topics.qmd~',
 'notes.qmd',
 '_quarto.yml',
 'notes.qmd~',
 'day4.org~',
 'push',
 'styles.css',
 'trainer.qmd',
 '.quarto',
 'index.qmd~',
 'day4.org',
 '_quarto.yml~',
 '_site',
 '.gitignore',
 'module1-day1.ipynb',
 'module1-day2.ipynb',
 'topics.qmd',
 'about.qmd',
 'module1-day3.ipynb',
 'Makefile~',
 'Makefile',
 '.ipynb_checkpoints',
 'module1-day4.ipynb']
for f in files:
    print(f, os.path.getsize(f))
index.qmd 677
topics.qmd~ 1043
notes.qmd 229
_quarto.yml 565
notes.qmd~ 200
day4.org~ 54
push 0
styles.css 17
trainer.qmd 1193
.quarto 4096
index.qmd~ 141
day4.org 84
_quarto.yml~ 525
_site 4096
.gitignore 29
module1-day1.ipynb 50000
module1-day2.ipynb 56885
topics.qmd 897
about.qmd 40
module1-day3.ipynb 50772
Makefile~ 586
Makefile 659
.ipynb_checkpoints 4096
module1-day4.ipynb 27846
max(files) # by dictionary order
'trainer.qmd'
max(files, key=os.path.getsize)
'module1-day2.ipynb'
import math
import math as m # here m becomes the math module
m.pi
3.141592653589793
from math import sin
sin(3.14/2)
0.9999996829318346

problem

  • Write a function longlistdir which will print filenames and folder names in a given folder, such that before every folder it prints a charecter d, and before every file it prints f.
    >>> longlistdir("/home/vikrant/training")
    d arcesium_batch1_module1
    f notes.txt
    f hello.py
    f scratch.ipynb
def print_parity(numbers):
    for n in numbers:
        if n%2 == 0:
            print("even", n)
        else:
            print("odd", n)
print_parity(nums)
odd 1
even 2
odd 3
odd 5
odd 7
odd 11
odd 13
def print_file_dir(files):
    for filename in files:
        if os.path.isfile(filename):
            print("f", filename)
        else:
            print("d", filename)
files = os.listdir()
print_file_dir(files)
f index.qmd
f topics.qmd~
f notes.qmd
f _quarto.yml
f notes.qmd~
f day4.org~
f push
f styles.css
f trainer.qmd
d .quarto
f index.qmd~
f day4.org
f _quarto.yml~
d _site
f .gitignore
f module1-day1.ipynb
f module1-day2.ipynb
f topics.qmd
f about.qmd
f module1-day3.ipynb
f Makefile~
f Makefile
d .ipynb_checkpoints
f module1-day4.ipynb
def longlistdir(path):
    files = os.listdir(path)
    print_file_dir(files)
longlistdir("/home/vikrant/trainings/")
d 2023
d 2018
d nakul
d day5.org
d 2022
d hello.py
d day5.org~
d 2024
d selenium_code_for_team
d 2020
d trainingvenv
d 2021
d 2019
d 2025
d 2017
d indexdata.xlsx
d selenium_venv
os.path.isfile("x.txt")
False
os.path.isdir("Desktop") # this is relative path
False
os.path.isdir("/home/vikrant/Desktop/")
True
longlistdir(os.getcwd())
f index.qmd
f topics.qmd~
f notes.qmd
f _quarto.yml
f notes.qmd~
f day4.org~
f push
f styles.css
f trainer.qmd
d .quarto
f index.qmd~
f day4.org
f _quarto.yml~
d _site
f .gitignore
f module1-day1.ipynb
f module1-day2.ipynb
f topics.qmd
f about.qmd
f module1-day3.ipynb
f Makefile~
f Makefile
d .ipynb_checkpoints
f module1-day4.ipynb
def longlistdir_(path):
    files = os.listdir(path)
    for filename in files:
        filepath = os.path.join(path, filename)
        if os.path.isfile(filepath):
            print("f", filename)
        else:
            print("d", filename)
longlistdir_("/home/vikrant/trainings/")
d 2023
d 2018
d nakul
f day5.org
d 2022
f hello.py
f day5.org~
d 2024
d selenium_code_for_team
d 2020
d trainingvenv
d 2021
d 2019
d 2025
d 2017
f indexdata.xlsx
d selenium_venv

Homework

  • Write function nrandoms which generates n random numbers bewteen 0 to 1.
>>> nrandoms(5)
[0.3180185315734232, 0.19816999876078534, 0.6549675992714722, 0.2966844056529988, 0.5773329096505485]
  • Write a function findlens which finds lengths of every word from a given list of words.
>>> findlens(["one", "two", "three"])
[3, 3, 5]
  • Write a function find_words_of_len to find words of given length from given list.
>>> find_words_of_len(words, 3)
['one', 'two', 'six']
  • Write a function findfiles which finds all files in given directory recursively with given extension.::
>>> findfiles("/var/", "log")
['/var/log/bootstrap.log',
'/var/log/alternatives.log',
'/var/log/dpkg.log',
'/var/log/apt/term.log',
'/var/log/apt/history.log']
  • Write a function greeting which greets randomly in variaus ways::
>>> greeting("Vikrant")
"Hello Vikrant"
>>> greeting("Vikrant")
"Namaste Vikrant"
>>> greeting("Vikrant")
"Good day Vikrant"
>>> greeting("Vikrant")
"Guten morgen Vikrant"