Welcome Back
!figlet Welcome to Session 2
__ __ _ _
\ \ / /__| | ___ ___ _ __ ___ ___ | |_ ___
\ \ /\ / / _ \ |/ __/ _ \| '_ ` _ \ / _ \ | __/ _ \
\ V V / __/ | (_| (_) | | | | | | __/ | || (_) |
\_/\_/ \___|_|\___\___/|_| |_| |_|\___| \__\___/
____ _ ____
/ ___| ___ ___ ___(_) ___ _ __ |___ \
\___ \ / _ \/ __/ __| |/ _ \| '_ \ __) |
___) | __/\__ \__ \ | (_) | | | | / __/
|____/ \___||___/___/_|\___/|_| |_| |_____|
Review of Last Session
Any questions?
A small problem.
Problem: Countdown
Write a program countdown.py to print numbers from n to 1.
You can verify your solution using:
%verify_problem countdown
The program should take the number n as command-line argument.
$ python countdown.py 5
5
4
3
2
1
%%file countdown.py
print(1)
%verify_problem countdown
ERROR: Unable to find program countdown.py.
Functions, Methods and Modules
Python has many built-in functions.
Python doesn’t support operations on incompatible datatypes.
TypeError: unsupported operand type(s) for +: 'int' and 'str'
Example: counting the number of digits in a number
How to count the number of digits in a number?
10715086071862673209484250490600018105614048117055336074437503883703510511249361224931983788156958581275946729175531468251871452856923140435984577574698574803934567774824230985421074605062371141877954182153046474983581941267398767559165543946077062914571196477686542167660429831652624386837205668069376
Writing our own functions
def square(x):
return x*x
def square(x):
y = x*x
return y
Problem: Cube
Write a function cube to compute cube of a number.
>>> cube(2)
8
You can verify your solution using:
%verify_problem cube
ERROR: Unable to find function with name cube.
Print vs Return
def square1(x):
return x*x
def square2(x):
print(x*x)
TypeError: unsupported operand type(s) for +: 'int' and 'NoneType'
Functions are values too!
def square(x):
return x*x
TypeError: square() missing 1 required positional argument: 'x'
<function __main__.square(x)>
<function __main__.square(x)>
<function __main__.square(x)>
def square(x):
return x*x
def sum_of_squares(x, y):
return square(x) + square(y)
def cube(x):
return x*x*x
def sum_of_cubes(x, y):
return cube(x) + cube(y)
def sq1(x):
return x*x
def sq2(y):
return y*y
If you notice, the sum_of_squares and sum_of_cubes are almost the same.
Can we generalize these two functions into a single one?
def sumof(f, x, y):
return f(x) + f(y)
sumof(len, "hello", "python")
functions = [square, cube]
[<function __main__.square(x)>, <function __main__.cube(x)>]
<function __main__.square(x)>
Passing functions as arguments is so useful that there are many built-in functions that accept functions as arguments.
max(["one", "two", "three", "four", "five"])
What if I want to find the longest one?
max(["one", "two", "three", "four", "five"], key=len)
def mylen(word):
print("mylen", word)
return len(word)
max(["one", "two", "three", "four", "five"], key=mylen)
mylen one
mylen two
mylen three
mylen four
mylen five
# with key=len
len("two") < len("three")
Methods
Methods are special kind of functions that work on a value/object.
upper is a method available on objects of type str.
AttributeError: 'int' object has no attribute 'upper'
"mathematics".count("mat")
"mathematics".replace("mat", "rat")
Spliting and joining strings
sentence = "Antyhing that can go wrong, will go wrong."
['Antyhing', 'that', 'can', 'go', 'wrong,', 'will', 'go', 'wrong.']
def wordcount(sentence):
return len(sentence.split())
sentences = [
"one two three",
"one two three four",
"one two three four five",
"a b c d e f g"]
max(sentences, key=wordcount)
sentence.split() # split on any white space
['Antyhing', 'that', 'can', 'go', 'wrong,', 'will', 'go', 'wrong.']
sentence.split(",") # split on the given delimiter
['Antyhing that can go wrong', ' will go wrong.']
Let’s see how to join the strings back.
"-".join(["a", "b", "c"])
":".join(["a", "b", "c"])
sep.join(["a", "b", "c"])
Modules
'Mon Sep 25 05:25:51 2023'
'Mon Sep 25 05:25:56 2023'
<module 'time' (built-in)>
<module 'time' (built-in)>
<module 'time' (built-in)>
'Mon Sep 25 05:26:43 2023'
Mon Sep 25 05:27:12 AM UTC 2023
Let’s see how to implement it in Python.
%%file date.py
import time
print(time.asctime())
Mon Sep 25 05:27:48 AM UTC 2023
The os module
['index.qmd',
'assignments.qmd',
'assignment-01.qmd',
'_quarto.yml',
'_book',
'course.qmd',
'references.qmd',
'.ipynb_checkpoints',
'date.py',
'args.py',
'styles.css',
'echo.py',
'syllabus.qmd',
'countdown.py',
'session2.ipynb',
'square.py',
'.quarto',
'lab.qmd',
'script.js',
'session1.ipynb.invalid',
'schedule.qmd',
'session1.ipynb',
'hello.py',
'live-notes.qmd',
'schedule.ipynb',
'references.bib']
# os.path.getsize("session-02.ipynb")
os.path.getsize("session2.ipynb")