Module II - Day 3

Python Made Easy: Science and Math Edition

Sep-Dec 2025 batch, Vikrant Patil

Date: 15 Nov 2025

Click here for All Notes

© Vikrant Patil

! allows executing system command from jupyter

!ls
about.qmd~      module1-day5.ipynb  square.py
cat.py          module2-day1.ipynb  students-module1-day2.ipynb
copyzen.txt     module2-day3.ipynb  students-module1-day3.ipynb
head.py         notes.qmd       students-module1-day4.ipynb
hello.py        notes.qmd~      students-module2-day2.ipynb
index.qmd       poem.txt        styles.css
index.qmd~      power.py        test_args.py
Makefile        promotions      testargs.py
Makefile~       push        today.org
maths_test_new.py   __pycache__     topics.qmd
maths_test.py       _quarto.yml     topics.qmd~
module1-day1.ipynb  _quarto.yml~    trainer.qmd
module1-day2.ipynb  revision.ipynb  trainer.qmd~
module1-day3.ipynb  say_hello.py    x.txt
module1-day4.ipynb  _site       zen.txt
%%file helloworld.py
print("Hello world!")
Writing helloworld.py
%%file args1.py
import sys

print(sys.argv)
Writing args1.py
!python args1.py vikrant
['args1.py', 'vikrant']
!python args1.py vikrant anil
['args1.py', 'vikrant', 'anil']

!python args1.py vikrant -n 5

%%file hello_person.py
import sys
name = sys.argv[1]

print("Hello", name)
Writing hello_person.py
!python hello_person.py vikrant
Hello vikrant
%%file welcome_multi_lingual.py
import sys
lang = sys.argv[1]
name = sys.argv[2]

if lang == 'marathi':
    print("नमस्कार", name)
elif lang == "english":
    print("hello", name)
elif lang == "Tamil":
    print("Wannakam", name)
else:
    print("Unknown langualge")

Writing welcome_multi_lingual.py
!python welcome_multi_lingual.py marathi vikrant
नमस्कार vikrant
!python welcome_multi_lingual.py Tamil vikrant
Wannakam vikrant

Assignment Problems

Write a python script chaos.py which prints first 10 iterations of x which is computed using follwing logic. To start with some value of x is given by user (from command line arguments). After that for each iteration new value of x is generated using the equation x = 3.9 * x * (1 - x) after computing new value of x print it to screen. See what happens to value of x at 10 itertion for different starting values of x i.e. 0.24, 0.25, 0.26, 0.3 etc.

python chaos.py 0.25
0.731250
0.766441
0.698135
0.821896
0.570894
0.955399
x = 0
for i in range(5):
    x = x + 1
    print(x)
1
2
3
4
5
%%file test_prog.py
import sys

def poly(x):
    return x**2 + 2*x + 1

n = float(sys.argv[1])
poly(n)
Writing test_prog.py
!python test_prog.py 10
x = input("Enter value for x:")
Enter value for x: 5
x
'5'
%%file test_prog.py
import sys

def poly(x):
    return x**2 + 2*x + 1

n = float(sys.argv[1])
print(poly(n))
Overwriting test_prog.py
!python test_prog.py 10
121.0
def twice(x):
    return 2*x

def double(x):
    print(2*x)
twice(5)
10
double(5)
10
x2 = twice(46)
x2
92
y = double(46)
92
print(y)
None
- give x first
- do this 10 times x = 3.9 * x * (1 - x)
- every time computations is done print value of x
%%file chaos.py
import sys

x = float(sys.argv[1])

for i in range(10):
    x = 3.9*x*(1-x)
    print(x)
Writing chaos.py
!python chaos.py 0.24
0.71136
0.80077510656
0.6221839075679007
0.916777261652611
0.2975571852604691
0.8151659363653104
0.5876146869644107
0.9450622998497004
0.2024862420847321
0.6297936990194279
%%file chaos.py
import sys

def chaotic_function(x):
    return 3.9*x*(1-x)


x = float(sys.argv[1])

for i in range(10):
    x = chaotic_function(x) 
    print(x)
Overwriting chaos.py
!python chaos.py 0.25
0.73125
0.76644140625
0.6981350104385375
0.8218958187902304
0.5708940191969317
0.9553987483642099
0.166186721954413
0.5404179120617926
0.9686289302998042
0.11850901017563877
%%file chaos.py
import sys

def chaotic_function(x):
    return 3.9*x*(1-x)

def run_iteration(x, n):
    for i in range(n):
        x = chaotic_function(x) 
        print(x)    

x = float(sys.argv[1])
run_iteration(x, 10)
Overwriting chaos.py
!python chaos.py 0.25
0.73125
0.76644140625
0.6981350104385375
0.8218958187902304
0.5708940191969317
0.9553987483642099
0.166186721954413
0.5404179120617926
0.9686289302998042
0.11850901017563877
import os
import random
import chaos
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
Cell In[35], line 1
----> 1 import chaos

File ~/programming/work/github/vikrant.dev/python-made-easy-science-math/chaos.py:11
      8         x = chaotic_function(x) 
      9         print(x)    
---> 11 x = float(sys.argv[1])
     12 run_iteration(x, 10)

ValueError: could not convert string to float: '-f'
import sys
sys.argv
['/home/vikrant/usr/local/default/lib/python3.11/site-packages/ipykernel_launcher.py',
 '-f',
 '/home/vikrant/.local/share/jupyter/runtime/kernel-97c6988b-3a90-4129-9300-6332bef11f67.json']
%%file chaos.py
import sys

def chaotic_function(x):
    return 3.9*x*(1-x)

def run_iteration(x, n):
    for i in range(n):
        x = chaotic_function(x) 
        print(x)    

if __name__ == "__main__":
    x = float(sys.argv[1])
    run_iteration(x, 10)
Overwriting chaos.py
import chaos
chaos.run_iteration(0.3, 15)
0.819
0.5781321000000001
0.951191962303401
0.18106067129594494
0.5782830479626462
0.9510998811665442
0.18138469912496583
0.5790887311884146
0.950605393136126
0.1831236407388855
0.5833985544715422
0.9478742563370232
0.19269373699117803
0.6066951567906556
0.930602959717928
%%file chaos1.py
import chaos
import sys

if __name__ == "__main__":
    x = float(sys.argv[1])
    n = int(sys.argv[2])
    chaos.run_iteration(x, n)
Writing chaos1.py
!python chaos1.py 0.24 7
0.71136
0.80077510656
0.6221839075679007
0.916777261652611
0.2975571852604691
0.8151659363653104
0.5876146869644107

Write a python script tail.py which will print last 5 lines of a file. this is how it should work.

$ python tail.py zen.txt
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!
nums = [1, 2, 3, 4, 5, 6, 7, 8, 10]
nums[0]
1
len(nums)
9
l = len(nums)
nums[l - 1]
10
nums[l - 2]
8
nums[l - 3]
7
nums[l - 4]
6
%%file tail.py
import sys

def print_last_n(items, n):
    l = len(items)
    for i in range(1, n+1):
        print(items[l - i])

def print_last_10lines(filename):
    with open(filename) as f:
        lines = []
        for line in f:
            lines.append(line.strip())

        print_last_n(lines, 10)
        


if __name__ == "__main__":
    filepath = sys.argv[1]
    print_last_10lines(filepath)
Overwriting tail.py
!python tail.py zen.txt
Namespaces are one honking great idea -- let's do more of those!
If the implementation is easy to explain, it may be a good idea.
If the implementation is hard to explain, it's a bad idea.
Although never is often better than *right* now.
Now is better than never.
Although that way may not be obvious at first unless you're Dutch.
There should be one-- and preferably only one --obvious way to do it.
In the face of ambiguity, refuse the temptation to guess.
Unless explicitly silenced.
Errors should never pass silently.
%%file tail.py
import sys


def print_last_10lines(filename):
    with open(filename) as f:
        lines = []
        for line in f:
            lines.append(line.strip())
            if len(lines) > 10:
                lines.pop(0)

        for line in lines:
            print(line)


if __name__ == "__main__":
    filepath = sys.argv[1]
    print_last_10lines(filepath)
Overwriting tail.py
nums
[2, 3, 4, 5, 6, 7, 8, 10]
nums.pop(0)
2
nums
[3, 4, 5, 6, 7, 8, 10]
!python tail.py zen.txt 
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!
%%file tail.py
import sys


def tail(filename, n):
    with open(filename) as f:
        lines = []
        for line in f:
            lines.append(line.strip())
            if len(lines) > n:
                lines.pop(0)

        for line in lines:
            print(line)


if __name__ == "__main__":
    n = int(sys.argv[1])
    filepath = sys.argv[2]
    tail(filepath, n)
Overwriting tail.py
!python tail.py 5 zen.txt
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!
import tail
tail.tail("/home/vikrant/programming/work/github/vikrant.dev/python-made-easy-science-math/zen.txt", 3)
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!

list slicing

nums = [2, 3, 1, 3, 1, 35, 3, 1, 8,0]
nums
[2, 3, 1, 3, 1, 35, 3, 1, 8, 0]
nums[0]
2
list(range(1, 5))
[1, 2, 3, 4]
nums[0:5] # start at index 0 and stop at index 4
[2, 3, 1, 3, 1]
nums
[2, 3, 1, 3, 1, 35, 3, 1, 8, 0]
nums[3:7] # start at index 3 and stop at index 6
[3, 1, 35, 3]
nums[2:] # drop first 2 items
[1, 3, 1, 35, 3, 1, 8, 0]
nums[:5] # take first 5 items
[2, 3, 1, 3, 1]
nums[len(nums)-3:] # last 3 items
[1, 8, 0]
def tail(filename, n):
    with open(filename) as f:
        lines = f.readlines()
        last_n_lines = lines[len(lines)-n:] # this is adavantage is due to list slicing
        for line in last_n_lines:
            print(line, end="")
tail("zen.txt", 5)
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!

iteration patterns

## accumulation ... you make one single item from given 
s = 0
for i in nums:
    s = s + i
print(s)
57
sqr = []
for i in nums:
    sqr.append(i*i)
print(sqr)
[4, 9, 1, 9, 1, 1225, 9, 1, 64, 0]
with open("zen.txt") as f:
    linenum = 1
    for line in f:
        print(linenum, line, end="")
        linenum += 1
1 The Zen of Python, by Tim Peters
2 
3 Beautiful is better than ugly.
4 Explicit is better than implicit.
5 Simple is better than complex.
6 Complex is better than complicated.
7 Flat is better than nested.
8 Sparse is better than dense.
9 Readability counts.
10 Special cases aren't special enough to break the rules.
11 Although practicality beats purity.
12 Errors should never pass silently.
13 Unless explicitly silenced.
14 In the face of ambiguity, refuse the temptation to guess.
15 There should be one-- and preferably only one --obvious way to do it.
16 Although that way may not be obvious at first unless you're Dutch.
17 Now is better than never.
18 Although never is often better than *right* now.
19 If the implementation is hard to explain, it's a bad idea.
20 If the implementation is easy to explain, it may be a good idea.
21 Namespaces are one honking great idea -- let's do more of those!
with open("zen.txt") as f:
    for i, line in enumerate(f):
        print(i, line, end="")
0 The Zen of Python, by Tim Peters
1 
2 Beautiful is better than ugly.
3 Explicit is better than implicit.
4 Simple is better than complex.
5 Complex is better than complicated.
6 Flat is better than nested.
7 Sparse is better than dense.
8 Readability counts.
9 Special cases aren't special enough to break the rules.
10 Although practicality beats purity.
11 Errors should never pass silently.
12 Unless explicitly silenced.
13 In the face of ambiguity, refuse the temptation to guess.
14 There should be one-- and preferably only one --obvious way to do it.
15 Although that way may not be obvious at first unless you're Dutch.
16 Now is better than never.
17 Although never is often better than *right* now.
18 If the implementation is hard to explain, it's a bad idea.
19 If the implementation is easy to explain, it may be a good idea.
20 Namespaces are one honking great idea -- let's do more of those!
for i, n in enumerate(nums):
    print(i, n)
0 2
1 3
2 1
3 3
4 1
5 35
6 3
7 1
8 8
9 0
students = ["Alice", "Alex", "Hans", "Liya", "Luke"]
for rollnum, name in enumerate(students, start=1):
    print(rollnum, name)
1 Alice
2 Alex
3 Hans
4 Liya
5 Luke
for student in reversed(students):
    print(student)
Luke
Liya
Hans
Alex
Alice
students
['Alice', 'Alex', 'Hans', 'Liya', 'Luke']
for i, student in reversed(enumerate(students)):
    print(i, student)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
Cell In[108], line 1
----> 1 for i, student in reversed(enumerate(students)):
      2     print(i, student)

TypeError: 'enumerate' object is not reversible
enumerate?
Init signature: enumerate(iterable, start=0)
Docstring:     
Return an enumerate object.
  iterable
    an object supporting iteration
The enumerate object yields pairs containing a count (from start, which
defaults to zero) and a value yielded by the iterable argument.
enumerate is useful for obtaining an indexed list:
    (0, seq[0]), (1, seq[1]), (2, seq[2]), ...
Type:           type
Subclasses:     
nums
[2, 3, 1, 3, 1, 35, 3, 1, 8, 0]
nums[1:8:2]
[3, 3, 35, 1]
nums[::2]
[2, 1, 1, 3, 8]
nums
[2, 3, 1, 3, 1, 35, 3, 1, 8, 0]
nums[::3]
[2, 3, 3, 0]
nums[::-1] # this is revered list!
[0, 8, 1, 3, 35, 1, 3, 1, 3, 2]
nums[-1]
0
nums[::-1]
[0, 8, 1, 3, 35, 1, 3, 1, 3, 2]