10  Module 1 - Day 5

Topics

For today’s practice make use of notebook module1-day5.ipynb created in your enviroment. Shut down kernel for all previous notebooks by right cliking on notbeook on left hand side file browser.

10.1 Writing own modules

%%file stats.py
import math 

def mean(numbers):
    return sum(numbers)/len(numbers)

def std(numbers):
    m = mean(numbers)
    s = 0
    for n in nums:
        s = s + (n-m)**2
    return math.sqrt(s/(len(nums)-1))

def median(numbers):
    numbers = sorted(numbers)
    n = len(numbers)
    c = n//2
    if n%2 == 0:
        return (numbers[c] + numbers[c-1])/2
    else:
        return numbers[c]
    
Overwriting stats.py
stats
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
Cell In[6], line 1
----> 1 stats

NameError: name 'stats' is not defined
import stats
stats.mean([1, 2, 3, 4, 5])
3.0
stats.median([1, 2, 3, 4, 5])
3
stats.std([1, 2, 3, 4, 5])
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
Cell In[10], line 1
----> 1 stats.std([1, 2, 3, 4, 5])

File /opt/arcesium-finop-25/website/live-notes/stats.py:9, in std(numbers)
      7 m = mean(numbers)
      8 s = 0
----> 9 for n in nums:
     10     s = s + (n-m)**2
     11 return math.sqrt(s/(len(nums)-1))

NameError: name 'nums' is not defined
%%file stats2.py
import math 

def mean(numbers):
    return sum(numbers)/len(numbers)

def std(numbers):
    m = mean(numbers)
    s = 0
    for n in numbers:
        s = s + (n-m)**2
    return math.sqrt(s/(len(numbers)-1))

def median(numbers):
    numbers = sorted(numbers)
    n = len(numbers)
    c = n//2
    if n%2 == 0:
        return (numbers[c] + numbers[c-1])/2
    else:
        return numbers[c]
    
Writing stats2.py
import stats2
stats2.std([1, 2, 3, 4, 5])
1.5811388300841898
"Hello World!"
'Hello World!'

10.2 Executing your standalone python programs

%%file hello.py

"Hello World!"
Writing hello.py
%%file hello.py

print("Hello World!")
Overwriting hello.py
%%file addnumbers.py

x = 10
y = 42
print(x+y)
Writing addnumbers.py
%%file add.py
x = float(input("Enter numeric value for x:"))
y = float(input("Enter numeric value for y:"))

print("Addition of numbers that you entered is:", x + y )
Overwriting add.py
%%file args.py
import sys

print(sys.argv) # this is a list which gets populated dynamically 
Writing args.py
%%file square.py
import sys

x = float(sys.argv[1]) # arguments are always text
print(x*x)
Writing square.py
!ls
__pycache__    hello.py        module1-day2.ipynb  square.py  test
add.py         hello.txt       module1-day3.ipynb  stats.py   test1
addnumbers.py  index.qmd       module1-day4.ipynb  stats1.py  txt1.txt
args.py        module1-day1.ipynb  module1-day5.ipynb  stats2.py  untitled.py
!cat add.py
x = float(input("Enter numeric value for x:"))
y = float(input("Enter numeric value for y:"))

print("Addition of numbers that you entered is:", x + y )
!python square.py 5
25.0
!python square.py 42
1764.0
import sys
sys.argv
['/opt/tljh/user/lib/python3.12/site-packages/ipykernel_launcher.py',
 '-f',
 '/home/jupyter-vikrant/.local/share/jupyter/runtime/kernel-8e79172c-5908-465e-99c9-beee6329157e.json']
%%file cube.py
import sys

x = sys.argv[1]
print(sys.argv)
print(x*x*x)
Overwriting cube.py
!python cube.py 5
['cube.py', '5']
Traceback (most recent call last):
  File "/opt/arcesium-finop-25/website/live-notes/cube.py", line 5, in <module>
    print(x*x*x)
          ~^~
TypeError: can't multiply sequence by non-int of type 'str'
'5'*'5'
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
Cell In[36], line 1
----> 1 '5'*'5'

TypeError: can't multiply sequence by non-int of type 'str'
!python square.py 54
2916.0
!python square.py 45
2025.0
%%file printwords.py
import sys
n = len(sys.argv)
for i in range(1, n):
    print(sys.argv[i])
Overwriting printwords.py
!python printwords.py  hello these are some words which my program will print
hello
these
are
some
words
which
my
program
will
print
!ls 
__pycache__    hello.py        module1-day3.ipynb  square.py  test1
add.py         hello.txt       module1-day4.ipynb  stats.py   txt1.txt
addnumbers.py  index.qmd       module1-day5.ipynb  stats1.py  untitled.py
args.py        module1-day1.ipynb  printwords,py       stats2.py
cube.py        module1-day2.ipynb  printwords.py       test
ones = [1]
ones[0]
1
ones[1]
---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
Cell In[47], line 1
----> 1 ones[1]

IndexError: list index out of range
Print('x')
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
Cell In[48], line 1
----> 1 Print('x')

NameError: name 'Print' is not defined
print("x")
x
sys. argv
['/opt/tljh/user/lib/python3.12/site-packages/ipykernel_launcher.py',
 '-f',
 '/home/jupyter-vikrant/.local/share/jupyter/runtime/kernel-8e79172c-5908-465e-99c9-beee6329157e.json']
import stats
stats.mean([1,2 ,3 , 4, 5])
3.0
!cat add.py
x = float(input("Enter numeric value for x:"))
y = float(input("Enter numeric value for y:"))

print("Addition of numbers that you entered is:", x + y )

10.2.1 reading text file from python

%%file hello.txt
hello
welcome
namaskar
Overwriting hello.txt
with open("hello.txt") as f:
    data = f.read()
data
'hello\nwelcome\nnamaskar\n'
print(data)
hello
welcome
namaskar
%%file cat.py
import sys

def cat(filepath):
    with open(filepath) as f:
        print(f.read())

filename = sys.argv[1]
cat(filename)
Writing cat.py
!python cat.py hello.txt
hello
welcome
namaskar
import cat
---------------------------------------------------------------------------
FileNotFoundError                         Traceback (most recent call last)
Cell In[60], line 1
----> 1 import cat

File /opt/arcesium-finop-25/website/live-notes/cat.py:8
      5         print(f.read())
      7 filename = sys.argv[1]
----> 8 cat(filename)

File /opt/arcesium-finop-25/website/live-notes/cat.py:4, in cat(filepath)
      3 def cat(filepath):
----> 4     with open(filepath) as f:
      5         print(f.read())

FileNotFoundError: [Errno 2] No such file or directory: '-f'
sys.argv
['/opt/tljh/user/lib/python3.12/site-packages/ipykernel_launcher.py',
 '-f',
 '/home/jupyter-vikrant/.local/share/jupyter/runtime/kernel-8e79172c-5908-465e-99c9-beee6329157e.json']
%%file cat1.py
import sys

def cat(filepath):
    with open(filepath) as f:
        print(f.read())


if __name__ == "__main__": # a magic variable ... python populates it automatically
    filename = sys.argv[1]
    cat(filename)
Writing cat1.py
import cat1
cat1.cat("hello.txt")
hello
welcome
namaskar
!python cat1.py hello.txt
hello
welcome
namaskar
%%file addnums.py
import sys

def convert_numeric(textnums):
    nums = []
    for t in textnums:
        nums.append(float(t))
    return nums

if __name__ == "__main__":
    numbers_text = sys.argv[1:]
    numbers = convert_numeric(numbers_text)
    print(sum(numbers))
Writing addnums.py
!python addnums.py 1 2 3 4 5 6 7 8 9
45.0
!python addnums.py 1 2 3 
6.0
import addnums
addnums.convert_numeric(['1', '2', '3'])
[1.0, 2.0, 3.0]

problem

Write a python script voice_of_wild.py which takes an argument of species name and prints the word associated with that species’s voice. Your program should support following species and their voice as given below::

  ===========   ====================================
  species          voice                              
  ===========   ====================================
  bird            chirp      
  bat             echolocation
  cat             meow
  dog             bark
  duck            quack
  any other       Not supported
  ===========   ====================================
voices = {"bird":"chirp",      
               "bat":"echolocation",
               "cat": "meow",
               "dog": "bark",
               "duck" : "quack"}
voices['bird']
'chirp'
voices['lion']
---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
Cell In[74], line 1
----> 1 voices['lion']

KeyError: 'lion'
voices.get('lion', "Not Supported!")
'Not Supported!'
voices.get('bat', "Not Supported!")
'echolocation'
%%file voice_of_wild.py
import sys

def voice(name):
    voices = {"bird":"chirp",      
               "bat":"echolocation",
               "cat": "meow",
               "dog": "bark",
               "duck" : "quack"}
    return voices.get(name, "Not Supported!")

if __name__ == "__main__":
    print(voice(sys.argv[1]))
Overwriting voice_of_wild.py
!python voice_of_wild.py cat
meow
!python voice_of_wild.py tiger
Not Supported!

10.3 building command line applications with typer

import typer
---------------------------------------------------------------------------
ModuleNotFoundError                       Traceback (most recent call last)
Cell In[85], line 1
----> 1 import typer

ModuleNotFoundError: No module named 'typer'
!python -m pip install typer
Defaulting to user installation because normal site-packages is not writeable

Collecting typer

  Downloading typer-0.20.0-py3-none-any.whl.metadata (16 kB)

Collecting click>=8.0.0 (from typer)

  Using cached click-8.3.1-py3-none-any.whl.metadata (2.6 kB)

Requirement already satisfied: typing-extensions>=3.7.4.3 in /opt/tljh/user/lib/python3.12/site-packages (from typer) (4.15.0)

Collecting shellingham>=1.3.0 (from typer)

  Downloading shellingham-1.5.4-py2.py3-none-any.whl.metadata (3.5 kB)

Collecting rich>=10.11.0 (from typer)

  Downloading rich-14.2.0-py3-none-any.whl.metadata (18 kB)

Collecting markdown-it-py>=2.2.0 (from rich>=10.11.0->typer)

  Downloading markdown_it_py-4.0.0-py3-none-any.whl.metadata (7.3 kB)

Requirement already satisfied: pygments<3.0.0,>=2.13.0 in /opt/tljh/user/lib/python3.12/site-packages (from rich>=10.11.0->typer) (2.19.2)

Collecting mdurl~=0.1 (from markdown-it-py>=2.2.0->rich>=10.11.0->typer)

  Downloading mdurl-0.1.2-py3-none-any.whl.metadata (1.6 kB)

Downloading typer-0.20.0-py3-none-any.whl (47 kB)

Using cached click-8.3.1-py3-none-any.whl (108 kB)

Downloading rich-14.2.0-py3-none-any.whl (243 kB)

Downloading shellingham-1.5.4-py2.py3-none-any.whl (9.8 kB)

Downloading markdown_it_py-4.0.0-py3-none-any.whl (87 kB)

Downloading mdurl-0.1.2-py3-none-any.whl (10.0 kB)

Installing collected packages: shellingham, mdurl, click, markdown-it-py, rich, typer

  WARNING: The script markdown-it is installed in '/home/jupyter-vikrant/.local/bin' which is not on PATH.

  Consider adding this directory to PATH or, if you prefer to suppress this warning, use --no-warn-script-location.

  WARNING: The script typer is installed in '/home/jupyter-vikrant/.local/bin' which is not on PATH.

  Consider adding this directory to PATH or, if you prefer to suppress this warning, use --no-warn-script-location.

Successfully installed click-8.3.1 markdown-it-py-4.0.0 mdurl-0.1.2 rich-14.2.0 shellingham-1.5.4 typer-0.20.0
import typer
---------------------------------------------------------------------------
ModuleNotFoundError                       Traceback (most recent call last)
Cell In[87], line 1
----> 1 import typer

ModuleNotFoundError: No module named 'typer'

let me restart the kernel!

import typer
!cat --help
Usage: cat [OPTION]... [FILE]...
Concatenate FILE(s) to standard output.

With no FILE, or when FILE is -, read standard input.

  -A, --show-all           equivalent to -vET
  -b, --number-nonblank    number nonempty output lines, overrides -n
  -e                       equivalent to -vE
  -E, --show-ends          display $ at end of each line
  -n, --number             number all output lines
  -s, --squeeze-blank      suppress repeated empty output lines
  -t                       equivalent to -vT
  -T, --show-tabs          display TAB characters as ^I
  -u                       (ignored)
  -v, --show-nonprinting   use ^ and M- notation, except for LFD and TAB
      --help        display this help and exit
      --version     output version information and exit

Examples:
  cat f - g  Output f's contents, then standard input, then g's contents.
  cat        Copy standard input to standard output.

GNU coreutils online help: <https://www.gnu.org/software/coreutils/>
Report any translation bugs to <https://translationproject.org/team/>
Full documentation <https://www.gnu.org/software/coreutils/cat>
or available locally via: info '(coreutils) cat invocation'
%%file addition.py
import typer

def add(x, y):
    return x + y


def cmd_add(x: int, y: int):
    print(add(x, y))
        
if __name__ == "__main__":
    typer.run(cmd_add)
Overwriting addition.py
!python addition.py --help
                                                                                

 Usage: addition.py [OPTIONS] X Y                                               

                                                                                

╭─ Arguments ──────────────────────────────────────────────────────────────────╮

│ *    x      INTEGER  [required]                                              │

│ *    y      INTEGER  [required]                                              │

╰──────────────────────────────────────────────────────────────────────────────╯

╭─ Options ────────────────────────────────────────────────────────────────────╮

│ --help          Show this message and exit.                                  │

╰──────────────────────────────────────────────────────────────────────────────╯


!python addition.py 5 10
15
%%file countdown.py
import typer

def countdown(end: int, start:int=0):
    n = end - start
    for i in range(n+1):
        print(end-i)


if __name__ == "__main__":
    typer.run(countdown)
    
Overwriting countdown.py
!python countdown.py --help
                                                                                

 Usage: countdown.py [OPTIONS] END                                              

                                                                                

╭─ Arguments ──────────────────────────────────────────────────────────────────╮

│ *    end      INTEGER  [required]                                            │

╰──────────────────────────────────────────────────────────────────────────────╯

╭─ Options ────────────────────────────────────────────────────────────────────╮

│ --start        INTEGER  [default: 0]                                         │

│ --help                  Show this message and exit.                          │

╰──────────────────────────────────────────────────────────────────────────────╯


!python countdown.py --start 3 8
8
7
6
5
4
3
!python countdown.py 8
8
7
6
5
4
3
2
1
0
%load_problem cube
Problem: Cube

Write a function cube to compute cube of a number.

>>> cube(2)
8

You can verify your solution using:

%verify_problem cube

# your code here
def cube(x):
    print(x**3)

%verify_problem cube
Found 4 checks
8
✗ cube(2)
  expected: 8
  found: None
27
✗ cube(3)
  expected: 27
  found: None
64
✗ cube(4)
  expected: 64
  found: None
125
✗ cube(5)
  expected: 125
  found: None
💥 Oops! Your solution to problem cube is incorrect or incomplete.
cube(5)
125
%load_problem command-mean
Problem: Statistical Mean

Write a program mean.py to compute statistical mean of all numbers given from command line.

$ python mean.py 1 2 3 4 5 
3.0

You can verify your solution using:

%verify_problem command-mean

%%file mean.py
# your code here


!python mean.py 1 2 3 4
python: can't open file '/opt/arcesium-finop-25/website/live-notes/mean.py': [Errno 2] No such file or directory