Module I - Day 3

Python Made Easy: Science and Math Edition

Sep-Dec 2025 batch, Vikrant Patil

Date: 04 Oct 2025

Click here for All Notes

© Vikrant Patil

quick recap

  • integers
  • real number (float)
  • list - numbered collection of object
  • dictionary - named collection of objects
stock = {"ticker": "INFY",
         "value": 235.5,
         "start": 230.0,
         "end": 235.5,
         "volume": 500}
stock['ticker']
'INFY'
stock['volume']
500
mixed_items = [1, 2, 3, 4, 5, 6, "hello", "words", 3.4]
mixed_items[0]
1
heights = [150, 151, 155, 148]
class_data = [{"name":"x", "height":150}, 
              {"name":"y", "height":151}, 
              {"name":"z", "height":155},
              {"name":"m", "height":148}]
            

methods

text = "These are some wise words!"
text.startswith("T")
True
x = 10
x
10
text.startswith("t") # python is case sensitive
False
x = 10
X
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
Cell In[15], line 1
----> 1 X

NameError: name 'X' is not defined
x
10
text.upper()
'THESE ARE SOME WISE WORDS!'
text
'These are some wise words!'
text.split() # it can take argument (input needed to execute the method) or it may be left empty
['These', 'are', 'some', 'wise', 'words!']
hyphened_text = "These-are-some-more-words"
hyphened_text.split("-")
['These', 'are', 'some', 'more', 'words']
comma_separated = "name,height,age,weight,blood pressure,sugar"
comma_separated.split()
['name,height,age,weight,blood', 'pressure,sugar']
comma_separated.split(",")
['name', 'height', 'age', 'weight', 'blood pressure', 'sugar']

filename extract filename from given filepath

linuxpath = "/home/vikrant/programming/training/module1-day3.ipynb"
linuxpath.split("/")
['', 'home', 'vikrant', 'programming', 'training', 'module1-day3.ipynb']
nums = [1, 2, 3, 4, 5, 6]
nums[-1]
6
linuxpath.split("/")[-1]
'module1-day3.ipynb'
tokens = linuxpath.split("/")
tokens[-1]
'module1-day3.ipynb'

extention FInd extension of a file given filename

filename = tokens[-1]
filename.split(".")
['module1-day3', 'ipynb']
filename.split(".")[-1]
'ipynb'
folder_seq = ['', 'home', 'vikrant', 'programming', 'training', 'module1-day3.ipynb']
"/".join(folder_seq)
'/home/vikrant/programming/training/module1-day3.ipynb'
",".join(folder_seq)
',home,vikrant,programming,training,module1-day3.ipynb'
quote = '"'
"\""
'"'
"\\"
'\\'
len("\\") # find lenght of text
1
"\n"
'\n'
"/".join(['home', 'vikrant', 'programming', 'training', 'module1-day3.ipynb'])
'home/vikrant/programming/training/module1-day3.ipynb'

problem - a poem is given as multiline string. can you convert in into a list of lines

poem="""The Zen of Python, by Tim Peters

Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
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!"""

::: {#4a768489-9bc3-4c09-a077-3cf0dcf7e65c .cell execution_count=50}
``` {.python .cell-code}
poem="""The Zen of Python, by Tim Peters

Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
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!"""

:::

lines = poem.split("\n")
lines
['The Zen of Python, by Tim Peters',
 '',
 'Beautiful is better than ugly.',
 'Explicit is better than implicit.',
 'Simple is better than complex.',
 'Complex is better than complicated.',
 'Flat is better than nested.',
 'Sparse is better than dense.',
 'Readability counts.',
 "Special cases aren't special enough to break the rules.",
 'Although practicality beats purity.',
 '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!"]
words = poem.split()
len(words) # it will length of list
144
len(lines)
21
len(poem)
856

some useful methods from list

odds = [1, 3, 5, 7, 9, 11, 13]
odds[0]
1
odds[0] = 3
odds
[3, 3, 5, 7, 9, 11, 13]
odds[0] = 1
odds
[1, 3, 5, 7, 9, 11, 13]
odds.append(15) # it will not print anything but it will do the work of appending 15 to the end of list
odds
[1, 3, 5, 7, 9, 11, 13, 15]
odds.pop() # it will remove last item and return it
15
odds
[1, 3, 5, 7, 9, 11, 13]
odds.count(3)
1
odds.index(7)
3
odds.reverse()
odds
[13, 11, 9, 7, 5, 3, 1]

built in functions

len("text")
4
len([1, 2, 3, 4, 5])
5
len(stock)
5
stock
{'ticker': 'INFY', 'value': 235.5, 'start': 230.0, 'end': 235.5, 'volume': 500}
len("text")
len([1, 2, 3, 4, 5])
len(stock)
5
x # repr - representation of the object
10
print(x)
10
poem
"The Zen of Python, by Tim Peters\n\nBeautiful is better than ugly.\nExplicit is better than implicit.\nSimple is better than complex.\nComplex is better than complicated.\nFlat is better than nested.\nSparse is better than dense.\nReadability counts.\nSpecial cases aren't special enough to break the rules.\nAlthough practicality beats purity.\nErrors should never pass silently.\nUnless explicitly silenced.\nIn the face of ambiguity, refuse the temptation to guess.\nThere should be one-- and preferably only one --obvious way to do it.\nAlthough that way may not be obvious at first unless you're Dutch.\nNow is better than never.\nAlthough never is often better than *right* now.\nIf the implementation is hard to explain, it's a bad idea.\nIf the implementation is easy to explain, it may be a good idea.\nNamespaces are one honking great idea -- let's do more of those!"
print(poem)
The Zen of Python, by Tim Peters

Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
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!
print("field1\tfild2\tfild3")
field1  fild2   fild3
print("field1\nfild2\nfild3")
field1
fild2
fild3
text
'These are some wise words!'
print(text)
These are some wise words!
print(odds)
[13, 11, 9, 7, 5, 3, 1]
odds
[13, 11, 9, 7, 5, 3, 1]
print(stock)
{'ticker': 'INFY', 'value': 235.5, 'start': 230.0, 'end': 235.5, 'volume': 500}
x, y = 0, 30 # assignment of two variables in single line
print(x, y)
0 30
print("test","hello")
test hello
print("test","hello", "another", "more", "word")
test hello another more word
type(x)
int
type(odds)
list
type(text)
str
42 # this is an integer and internally this is represeted as binary digits
42
"42" # text
'42'
a = 42
"42"
'42'
len("42")
2
len(42)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
Cell In[107], line 1
----> 1 len(42)

TypeError: object of type 'int' has no len()
line_from_file = "12,34,55,67"
line_from_file
'12,34,55,67'
int_tokens = line_from_file.split(",")
int_tokens
['12', '34', '55', '67']
int_tokens[0]
'12'
int(int_tokens[0])
12
"text" + "hello" # concatenation
'texthello'
"12" + "13"
'1213'
int("12") + int("13")
25
result = 42
type(result)
int
str(result)
'42'

problem find number of digits in decimal representation of 2**100

result
42
100
100
str(100)
'100'
len(  str(100)   )
len('100')
3
len(str(2**100))
31
2**100
1267650600228229401496703205376
a = 2**100
b = str(a)
len(b)
31
len(a)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
Cell In[131], line 1
----> 1 len(a)

TypeError: object of type 'int' has no len()
sum([1, 2, 3, 4, 5, 6, 7])
28
odss
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
Cell In[133], line 1
----> 1 odss

NameError: name 'odss' is not defined
odds
[13, 11, 9, 7, 5, 3, 1]
sum(odds)/len(odds)
7.0
max(odds)
13
min(odds)
1
  • len - find length of text, list, dictionary
  • print - print to screen
  • type - identify the type
  • str - convert the object into text
  • int -
  • float
  • sum
  • max
  • min

functions

def square(m): # next line is new code block
    sqr = m*m
    return sqr 
square(8)
64
square(10)
100
square(100)
10000
x
0
y
30
square(y)
900
v = square(99)
print(v)
9801
v
9801
None
def say_hello(name):
    print("hello", name)
say_hello("samiha")
hello samiha
x = say_hello("python")
hello python
print(x) # because the function does not have return statement!
None
def add(x, y):
    return x + y
add(4, 5)
9
add(6)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
Cell In[157], line 1
----> 1 add(6)

TypeError: add() missing 1 required positional argument: 'y'

problem

  • Write a function count_digits which takes integer as an argument to function and returns number of digits of that integer
[]: count_digits(100)
3
c = 5000
len(c)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
Cell In[159], line 2
      1 c = 5000
----> 2 len(c)

TypeError: object of type 'int' has no len()
len(5000)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
Cell In[160], line 1
----> 1 len(5000)

TypeError: object of type 'int' has no len()
"42"
'42'
"ytuywetrwey"
'ytuywetrwey'
"This"
'This'
"43"
'43'
len("42")
2
5000
5000
len("5000")
4
c = 10000
type(c)
int
c
10000
c
10000
c
10000
strc = str(c)
strc
'10000'
len(strc)
5
def func():
    x = 5
    y = 10
    x = y + 10
    return x
func()
20
func()
20
func(10)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
Cell In[180], line 1
----> 1 func(10)

TypeError: func() takes 0 positional arguments but 1 was given

Problems For Practice

  • Write a function compute_velocity which takes three arguments u, a , t where u is initial velocity in m/s, a is accelaration in m/s\(^2\) and t is time in seconds. It returns final velocity computed using newton’s laws of motion reresnted by this equation v = u + at. sample run is show below

    [ ]: compute_velocity(0, 9.8, 10)
    98
  • Here is a list of some built in functions , which means you don’t have to define them, they exist with python installation (we have seen few such functions e.g. print, type). Try them out by passing appropriate arguments as suggested.

    • len : finds length of a list/text like objects. len([1, 1, 2, 2, 3, 3]) will give 6 as result. len(“hello”) will give 5.
    • sum : finds sum of numbers from a list (if has all numbers in it). So you pass a desired list as argument to sum.e.g. sum([1,2,3]) will result into 6!
    • str : converts an integer or float to text format, so that every digit in the number becomes a text character
    • int : converts a text into a number for example if you want to make “1234” as 1234 use int("1234")
  • Now write a function mean which will finds out arithmatic mean of numbers given in a list. A function mean will have an argument numbers which is assumed to be a list. your function will compute mean of numbers from that list. here is one sample run of function.

    [ ]: mean([1,2,3,4,5])
    3.0