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.pyimport math def mean(numbers):returnsum(numbers)/len(numbers)def std(numbers): m = mean(numbers) s =0for n in nums: s = s + (n-m)**2return math.sqrt(s/(len(nums)-1))def median(numbers): numbers =sorted(numbers) n =len(numbers) c = n//2if n%2==0:return (numbers[c] + numbers[c-1])/2else:return numbers[c]
Overwriting stats.py
stats
---------------------------------------------------------------------------NameError Traceback (most recent call last)
CellIn[6], line 1----> 1statsNameError: 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)
CellIn[10], line 1----> 1stats.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----> 9for n innums:
10 s = s + (n-m)**2 11return math.sqrt(s/(len(nums)-1))
NameError: name 'nums' is not defined
%%file stats2.pyimport math def mean(numbers):returnsum(numbers)/len(numbers)def std(numbers): m = mean(numbers) s =0for n in numbers: s = s + (n-m)**2return math.sqrt(s/(len(numbers)-1))def median(numbers): numbers =sorted(numbers) n =len(numbers) c = n//2if n%2==0:return (numbers[c] + numbers[c-1])/2else: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.pyprint("Hello World!")
Overwriting hello.py
%%file addnumbers.pyx =10y =42print(x+y)
Writing addnumbers.py
%%file add.pyx =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.pyimport sysprint(sys.argv) # this is a list which gets populated dynamically
Writing args.py
%%file square.pyimport sysx =float(sys.argv[1]) # arguments are always textprint(x*x)
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 )
['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)
CellIn[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.pyimport sysn =len(sys.argv)for i inrange(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
---------------------------------------------------------------------------IndexError Traceback (most recent call last)
CellIn[47], line 1----> 1ones[1]IndexError: list index out of range
Print('x')
---------------------------------------------------------------------------NameError Traceback (most recent call last)
CellIn[48], line 1----> 1Print('x')
NameError: name 'Print' is not defined
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.txthellowelcomenamaskar
Overwriting hello.txt
withopen("hello.txt") as f: data = f.read()
data
'hello\nwelcome\nnamaskar\n'
print(data)
hello
welcome
namaskar
%%file cat.pyimport sysdef cat(filepath):withopen(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)
CellIn[60], line 1----> 1importcatFile /opt/arcesium-finop-25/website/live-notes/cat.py:8 5print(f.read())
7 filename = sys.argv[1]
----> 8cat(filename)File /opt/arcesium-finop-25/website/live-notes/cat.py:4, in cat(filepath) 3defcat(filepath):
----> 4withopen(filepath)as f:
5print(f.read())
FileNotFoundError: [Errno 2] No such file or directory: '-f'
%%file cat1.pyimport sysdef cat(filepath):withopen(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.pyimport sysdef convert_numeric(textnums): nums = []for t in textnums: nums.append(float(t))return numsif__name__=="__main__": numbers_text = sys.argv[1:] numbers = convert_numeric(numbers_text)print(sum(numbers))
Writing addnums.py
!python addnums.py 123456789
45.0
!python addnums.py 123
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
=========== ====================================
10.3 building command line applications with typer
import typer
---------------------------------------------------------------------------ModuleNotFoundError Traceback (most recent call last)
CellIn[85], line 1----> 1importtyperModuleNotFoundError: 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)
CellIn[87], line 1----> 1importtyperModuleNotFoundError: 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'
Usage: addition.py [OPTIONS] X Y
╭─ Arguments ──────────────────────────────────────────────────────────────────╮
│ * x INTEGER[required] │
│ * y INTEGER[required] │
╰──────────────────────────────────────────────────────────────────────────────╯
╭─ Options ────────────────────────────────────────────────────────────────────╮
│ --help Show this message and exit. │
╰──────────────────────────────────────────────────────────────────────────────╯
!python addition.py 510
15
%%file countdown.pyimport typerdef countdown(end: int, start:int=0): n = end - startfor i inrange(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 ────────────────────────────────────────────────────────────────────╮
│ --startINTEGER [default: 0] │
│ --help Show this message and exit. │
╰──────────────────────────────────────────────────────────────────────────────╯
!python countdown.py --start 38
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 heredef 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 1234
python: can't open file '/opt/arcesium-finop-25/website/live-notes/mean.py': [Errno 2] No such file or directory