Jan 16-20, 2023 Vikrant Patil
All notes are available online at https://notes.pipal.in/2023/arcesium_finop_jan/
Please login to https://engage.pipal.in/ and launch jupyter lab
For today create a notebook with name module1-day5
notebook names are case sensitive. Make sure you give correct name
© Pipal Academy LLP
>>> group([1, 2, 3, 4, 5, 6, 7, 8, 9], 3)
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
>>> group([1, 2, 3, 4, 5, 6, 7, 8, 9], 4)
[[1, 2, 3, 4], [5, 6, 7, 8], [9]]
nums = [4, 5, 73, 2, 5, 8]
for num in nums:
print(num, end=",")
4,5,73,2,5,8,
nums[:3] # first three
[4, 5, 73]
nums[3:6]
[2, 5, 8]
for i in range(len(nums)):
print(nums[i]) # i is index here
4 5 73 2 5 8
evens = list(range(2, 20, 2))
evens
[2, 4, 6, 8, 10, 12, 14, 16, 18]
evens[0::3]
[2, 8, 14]
evens[1::3]
[4, 10, 16]
nums[3:100] # if end is given beyond boundary .. then slicing does not fail..
[2, 5, 8]
nums[100]
--------------------------------------------------------------------------- IndexError Traceback (most recent call last) Cell In[13], line 1 ----> 1 nums[100] IndexError: list index out of range
[1, 2, 3, 4, 5, 6, 7]
[1, 2, 3, 4, 5, 6, 7]
[1, 2, 3], [4, 5, 6] , [7]
while condition:
code line 1
code line 2
chaning of condition
x = 5
while x!=0:
print(x)
# unless you change x ..in the loop so that it becomes 0 some time, this while loop will keep on exuecuting
x = x - 1
5 4 3 2 1
def myrange(n):
nums = []
while n>=0: # condition if not given correctly you will end with bugs in code!
n = n - 1
nums.append(n)
return nums
myrange(5)
[4, 3, 2, 1, 0, -1]
def myrange(n):
nums = []
n = n - 1
while n>=0: # condition if not given correctly you will end with bugs in code!
nums.append(n)
n = n - 1
nums.reverse()
return nums
myrange(5)
[0, 1, 2, 3, 4]
def myrange(n):
nums = []
while n>0: # condition if not given correctly you will end with bugs in code!
n = n - 1
nums.append(n)
nums.reverse()
return nums
myrange(5)
[0, 1, 2, 3, 4]
while True:
pass
--------------------------------------------------------------------------- KeyboardInterrupt Traceback (most recent call last) Cell In[29], line 1 ----> 1 while True: 2 pass KeyboardInterrupt:
$F_n$ = $F_n$$-$$_1$ + $F_n$$-$$_2$
current = prev_current + previous
prev_current = current
def print_fib(n):
"""
Print fibonnacci numbers less than n
"""
curr, prev = 1, 1
while prev < n:
print(prev, end=",")
curr, prev = prev+curr, curr
a, b, = 2, 3
print_fib(100)
1,1,2,3,5,8,13,21,34,55,89,
int("45") # these are available directly.. no need of import.. these are builtin functions
45
import math # this will import math module which has mathematics related functions
math.pi
3.141592653589793
math.sin(math.pi)
1.2246467991473532e-16
math.sqrt(4)
2.0
math.ceil(2.3)
3
math.floor(2.3)
2
import math
import math as m # you can give some nickname to your import
m.pi
3.141592653589793
from math import sin # only function is function is imported
sin(0)
0.0
del math # del actually is not anything to math module... but delinking the name math and math-module
math
--------------------------------------------------------------------------- NameError Traceback (most recent call last) Cell In[47], line 1 ----> 1 math NameError: name 'math' is not defined
import os
Where is this interpreter running
os.getcwd() # give me current working directory
'/home/vikrant/trainings/2023/arcesium_finop_jan'
current_folder = os.getcwd()
os.listdir(current_folder)
['index.html', 'test.ipynb', 'module1-day5.html', 'module1-day4.org', 'push', 'module1-day5.ipynb', 'Untitled.html', 'index.ipynb', 'module1-day1.html', 'other_files', 'module1-day1.ipynb', 'module1-day2.ipynb', 'test.html', 'module1-day3.html', 'module1-day2.html', 'module1-day3.ipynb', 'Makefile~', 'module1-day4.html', 'Makefile', '.ipynb_checkpoints', 'module1-day5.org', 'users.csv~', 'module1-day4.ipynb']
Some commonly used functionality from os module
os.listdir() # if not input /argument is given then by default current working directory listing is returned
['index.html', 'test.ipynb', 'module1-day5.html', 'module1-day4.org', 'push', 'module1-day5.ipynb', 'Untitled.html', 'index.ipynb', 'module1-day1.html', 'other_files', 'module1-day1.ipynb', 'module1-day2.ipynb', 'test.html', 'module1-day3.html', 'module1-day2.html', 'module1-day3.ipynb', 'Makefile~', 'module1-day4.html', 'Makefile', '.ipynb_checkpoints', 'module1-day5.org', 'users.csv~', 'module1-day4.ipynb']
help(os.getlogin)
Help on built-in function getlogin in module posix:
getlogin()
Return the actual login name.
os.path.isfile("index.html")
True
os.path.isfile(os.getcwd())
False
os.path.isdir(os.getcwd())
True
os.path.isfile(os.getcwd())
False
os.path
<module 'posixpath' from '/usr/lib/python3.10/posixpath.py'>
os.path.isfile("/home/vikrant/")
False
path = "c:\\program files\\python\\bin\\python.exe"
folder = "/home/vikrant/trainings/2023/arcesium_finop_jan"
os.path.sep
'/'
filepath = folder + os.path.sep + "index.html"
filepath
'/home/vikrant/trainings/2023/arcesium_finop_jan/index.html'
",".join(["one", "two"])
'one,two'
os.path.join(folder, "index.html")
'/home/vikrant/trainings/2023/arcesium_finop_jan/index.html'
os.path.join(folder, "other_files", "users.csv")
'/home/vikrant/trainings/2023/arcesium_finop_jan/other_files/users.csv'
os.path.join(os.getcwd(), "other_files", "users.csv")
'/home/vikrant/trainings/2023/arcesium_finop_jan/other_files/users.csv'
os.getlogin()
'vikrant'
os.mkdir("testdir") # relative path
complete_path = os.path.join(os.getcwd(), "testdir1") # just a text
complete_path # absoulute path... starts from c: (drive) on windows and / on unix/mac
'/home/vikrant/trainings/2023/arcesium_finop_jan/testdir1'
os.mkdir(complete_path)
import datetime
datetime.datetime(2023, 1, 20)
datetime.datetime(2023, 1, 20, 0, 0)
date = datetime.datetime(2023, 1, 20)
type(date) # this returns class of that object
datetime.datetime
x = 10
x + 45
55
date
datetime.datetime(2023, 1, 20, 0, 0)
date
datetime.datetime(2023, 1, 20, 0, 0)
help(datetime.timedelta)
Help on class timedelta in module datetime: class timedelta(builtins.object) | Difference between two datetime values. | | timedelta(days=0, seconds=0, microseconds=0, milliseconds=0, minutes=0, hours=0, weeks=0) | | All arguments are optional and default to 0. | Arguments may be integers or floats, and may be positive or negative. | | Methods defined here: | | __abs__(self, /) | abs(self) | | __add__(self, value, /) | Return self+value. | | __bool__(self, /) | True if self else False | | __divmod__(self, value, /) | Return divmod(self, value). | | __eq__(self, value, /) | Return self==value. | | __floordiv__(self, value, /) | Return self//value. | | __ge__(self, value, /) | Return self>=value. | | __getattribute__(self, name, /) | Return getattr(self, name). | | __gt__(self, value, /) | Return self>value. | | __hash__(self, /) | Return hash(self). | | __le__(self, value, /) | Return self<=value. | | __lt__(self, value, /) | Return self<value. | | __mod__(self, value, /) | Return self%value. | | __mul__(self, value, /) | Return self*value. | | __ne__(self, value, /) | Return self!=value. | | __neg__(self, /) | -self | | __pos__(self, /) | +self | | __radd__(self, value, /) | Return value+self. | | __rdivmod__(self, value, /) | Return divmod(value, self). | | __reduce__(...) | __reduce__() -> (cls, state) | | __repr__(self, /) | Return repr(self). | | __rfloordiv__(self, value, /) | Return value//self. | | __rmod__(self, value, /) | Return value%self. | | __rmul__(self, value, /) | Return value*self. | | __rsub__(self, value, /) | Return value-self. | | __rtruediv__(self, value, /) | Return value/self. | | __str__(self, /) | Return str(self). | | __sub__(self, value, /) | Return self-value. | | __truediv__(self, value, /) | Return self/value. | | total_seconds(...) | Total seconds in the duration. | | ---------------------------------------------------------------------- | Static methods defined here: | | __new__(*args, **kwargs) from builtins.type | Create and return a new object. See help(type) for accurate signature. | | ---------------------------------------------------------------------- | Data descriptors defined here: | | days | Number of days. | | microseconds | Number of microseconds (>= 0 and less than 1 second). | | seconds | Number of seconds (>= 0 and less than 1 day). | | ---------------------------------------------------------------------- | Data and other attributes defined here: | | max = datetime.timedelta(days=999999999, seconds=86399, microseconds=9... | | min = datetime.timedelta(days=-999999999) | | resolution = datetime.timedelta(microseconds=1)
oneday = datetime.timedelta(days=1)
date
datetime.datetime(2023, 1, 20, 0, 0)
date + oneday # next date
datetime.datetime(2023, 1, 21, 0, 0)
date.day
20
date.year
2023
date.second
0
date.hour
0
now = datetime.datetime.now() # get datetime instance for current time ...
now
datetime.datetime(2023, 1, 20, 11, 24, 44, 907082)
datetime.datetime.today()
datetime.datetime(2023, 1, 20, 11, 26, 11, 455696)
list(range(5))
[0, 1, 2, 3, 4]
def daterange(n):
today = datetime.datetime.today()
dates = []
for i in range(n):
dates.append(today + datetime.timedelta(i))
return dates
daterange(4)
[datetime.datetime(2023, 1, 20, 11, 32, 18, 210060), datetime.datetime(2023, 1, 21, 11, 32, 18, 210060), datetime.datetime(2023, 1, 22, 11, 32, 18, 210060), datetime.datetime(2023, 1, 23, 11, 32, 18, 210060)]
def add(x=1, y=0):
return x + y
add(2) # by order of arguments x = 2, y not given
2
add(2, 3) # x =1 , y =3 # positional arguments
5
add()
1
add(x=2, y=4) # named/keyword arguments
6
add(x=2, 5)
Cell In[123], line 1 add(x=2, 5) ^ SyntaxError: positional argument follows keyword argument
%%file test.txt
in this I have
some text data
Writing test.txt
%%file hello.py
print("Hello")
%%file test1.txt
UsageError: %%file is a cell magic, but the cell body is empty.
%%file hello.py
print("Hello")
Writing hello.py
!ls # with this I can run system commandd
hello.py module1-day2.html module1-day5.html test.html index.html module1-day2.ipynb module1-day5.ipynb test.ipynb index.ipynb module1-day3.html module1-day5.org test.txt Makefile module1-day3.ipynb other_files Untitled.html Makefile~ module1-day4.html push users.csv~ module1-day1.html module1-day4.ipynb testdir module1-day1.ipynb module1-day4.org testdir1
!python3 hello.py
Hello
%%file hello1.py
print("Hello Arcesium Finop Jan batch!")
Writing hello1.py
!python3 hello1.py
Hello Arcesium Finop Jan batch!
!python hello1.py
Hello Arcesium Finop Jan batch!
%%file args.py
import sys
sys.argv # this is a list which comes with the user arguments
print(sys.argv)
Writing args.py
!python args.py
['args.py']
!python args.py test1 test2 skjdhds kdsjfhkjds kjdshf
['args.py', 'test1', 'test2', 'skjdhds', 'kdsjfhkjds', 'kjdshf']
!python args.py arg1
['args.py', 'arg1']
!python args.py arg1 arg2
['args.py', 'arg1', 'arg2']
!python args.py arg1 arg2 arg3 # you can only pass space seperated arguments
['args.py', 'arg1', 'arg2', 'arg3']
!python args.py 1 2 3 4 5 # arguments are always text!
['args.py', '1', '2', '3', '4', '5']
%%file mysum.py
import sys
numargs = sys.argv[1:] # remember sys.argv is a list of text data
# 0th item is always python file name ...
s = 0
for n in numargs:
s = s + n
print(s)
Writing mysum.py
!python mysum.py 1 2 3 4 5
Traceback (most recent call last):
File "/home/vikrant/trainings/2023/arcesium_finop_jan/mysum.py", line 7, in <module>
s = s + n
TypeError: unsupported operand type(s) for +: 'int' and 'str'
%%file mysum.py
import sys
numargs = sys.argv[1:] # remember sys.argv is a list of text data
# 0th item is always python file name ...
s = 0
for n in numargs:
s = s + int(n)
print(s)
Overwriting mysum.py
!python mysum.py 1 2 3 4 5 6
21
%%file mysum.py
import sys
def mysum(nums):
s = 0
for n in nums:
s = s + int(n)
return s
numargs = sys.argv[1:] # remember sys.argv is a list of text data
# 0th item is always python file name ...
print(mysum(numargs))
Overwriting mysum.py
!python mysum.py 1 2 3 4
10
%%file greeting.py
import sys
print("hello", sys.argv[1])
Overwriting greeting.py
!python greeting.py vikrant
hello vikrant
!python greeting.py python
hello python
%%file basicstats.py
import sys
def mysum(nums):
s = 0
for n in nums:
s = s + n
return s
def std(nums):
pass
def mean(nums):
pass
def quantile(nums, percentage):
pass
def to_ints(numargs):
nums = []
for sn in numargs:
nums.append(int(sn))
return nums
numargs = sys.argv[1:] # remember sys.argv is a list of text data
# 0th item is always python file name ...
nums = to_ints(numargs)
print(mysum(nums))
print(std(nums))
print(mean(nums))
Overwriting basicstats.py
!python basicstats.py 1 2 3 4 5
15 None None