Python Virtual Training For Arcesium - Module I - Day 5

Aug 10-14, 2020 Vikrant Patil

These notes are available online at http://notes.pipal.in/2020/arcesium_finop_batch1_module1/day5.html

© Pipal Academy LLP

Day 1 | Day 2 | Day 3 | Day 4 | Day 5

We will be using jupyter hub from http://lab1.pipal.in for this training.

make use of notebook module1-day5.ipynb for today's session.

built in modules

In [1]:
import os
In [2]:
os.getcwd() # this would return current working directory /folder
Out[2]:
'/home/vikrant/trainings/2020/arcesium_finop_batch1_module1'
In [3]:
os.listdir() # lists files and directories in current folder
Out[3]:
['day2.html',
 'day5.html',
 'push',
 'day2.ipynb',
 'day1.html',
 'day5.ipynb',
 'day3.html',
 'day1.ipynb',
 'day4.html',
 'Makefile',
 '.ipynb_checkpoints',
 'day4.ipynb',
 'day3.ipynb']
In [4]:
os.listdir("/tmp")
Out[4]:
['timeshift',
 '.X11-unix',
 'skypeforlinux Crashes',
 'net-export',
 'systemd-private-d4ffc8c9c7ad447ba07ef6e0f5f3c05d-rtkit-daemon.service-4Zeopt',
 'systemd-private-d4ffc8c9c7ad447ba07ef6e0f5f3c05d-systemd-timesyncd.service-Gvwnrn',
 'Temp-19e8c0b6-caf8-49eb-ba05-b23f10768176',
 'bluejeans-v2 Crashes',
 'config-err-c8Dust',
 'github-2020714-3753-h7debi.ppx7',
 'skype-1715',
 'ssh-zvGCefozq2rF',
 'github-2020714-6289-rbmab3.eou2',
 'Temp-4ed6d016-d3f1-4fdc-811a-ac3f96fba48e',
 '.org.chromium.Chromium.Zv1uxX',
 '.XIM-unix',
 'Atom Crashes',
 'systemd-private-d4ffc8c9c7ad447ba07ef6e0f5f3c05d-bolt.service-epIEuJ',
 '.Test-unix',
 '.font-unix',
 '.org.chromium.Chromium.xjWkRq',
 '.X0-lock',
 '.org.chromium.Chromium.bg1VrM',
 '.ICE-unix',
 '.org.chromium.Chromium.fjXAhb',
 '.org.chromium.Chromium.7kmgr7',
 'systemd-private-d4ffc8c9c7ad447ba07ef6e0f5f3c05d-colord.service-tJqwYo',
 '.org.chromium.Chromium.iXND5P',
 'systemd-private-d4ffc8c9c7ad447ba07ef6e0f5f3c05d-ModemManager.service-G9a2dy',
 'mintUpdate',
 'systemd-private-d4ffc8c9c7ad447ba07ef6e0f5f3c05d-systemd-resolved.service-b99q7c']
In [5]:
os.path.join("/", "home", "vikrant")
Out[5]:
'/home/vikrant'
In [6]:
os.path.exists("/home/vikrant/")
Out[6]:
True
In [7]:
os.path.getsize("/home/vikrant/Documents/acer.txt")
Out[7]:
191
In [8]:
os.path.join("x","y")
Out[8]:
'x/y'
In [10]:
cwd = os.getcwd()
path = os.path.join(cwd, "x", "y")
In [11]:
os.getcwd()
Out[11]:
'/home/vikrant/trainings/2020/arcesium_finop_batch1_module1'
In [12]:
path
Out[12]:
'/home/vikrant/trainings/2020/arcesium_finop_batch1_module1/x/y'
In [13]:
path1 = os.path.join(cwd, "test")
In [14]:
path1
Out[14]:
'/home/vikrant/trainings/2020/arcesium_finop_batch1_module1/test'
In [15]:
os.mkdir(path1)
In [16]:
!ls
day1.html   day2.html	day3.html   day4.html	day5.html   Makefile  test
day1.ipynb  day2.ipynb	day3.ipynb  day4.ipynb	day5.ipynb  push
In [17]:
os.path.exists(path1)
Out[17]:
True
In [18]:
path2 = os.path.join(cwd, "test1")
In [19]:
path2
Out[19]:
'/home/vikrant/trainings/2020/arcesium_finop_batch1_module1/test1'
In [20]:
!ls
day1.html   day2.html	day3.html   day4.html	day5.html   Makefile  test
day1.ipynb  day2.ipynb	day3.ipynb  day4.ipynb	day5.ipynb  push
In [21]:
os.path.exists(path2)
Out[21]:
False
In [22]:
filename = "acer.txt"
In [23]:
path = os.path.join("/","home","vikrant","Documents",filename)
In [24]:
path
Out[24]:
'/home/vikrant/Documents/acer.txt'
In [26]:
import os
In [30]:
for path, dirs, files in os.walk(os.getcwd()):
    for f in files:
        print(os.path.join(path,f))
/home/vikrant/trainings/2020/arcesium_finop_batch1_module1/day2.html
/home/vikrant/trainings/2020/arcesium_finop_batch1_module1/day5.html
/home/vikrant/trainings/2020/arcesium_finop_batch1_module1/push
/home/vikrant/trainings/2020/arcesium_finop_batch1_module1/day2.ipynb
/home/vikrant/trainings/2020/arcesium_finop_batch1_module1/day1.html
/home/vikrant/trainings/2020/arcesium_finop_batch1_module1/day5.ipynb
/home/vikrant/trainings/2020/arcesium_finop_batch1_module1/day3.html
/home/vikrant/trainings/2020/arcesium_finop_batch1_module1/day1.ipynb
/home/vikrant/trainings/2020/arcesium_finop_batch1_module1/day4.html
/home/vikrant/trainings/2020/arcesium_finop_batch1_module1/Makefile
/home/vikrant/trainings/2020/arcesium_finop_batch1_module1/day4.ipynb
/home/vikrant/trainings/2020/arcesium_finop_batch1_module1/day3.ipynb
/home/vikrant/trainings/2020/arcesium_finop_batch1_module1/.ipynb_checkpoints/day1-checkpoint.html
/home/vikrant/trainings/2020/arcesium_finop_batch1_module1/.ipynb_checkpoints/day3-checkpoint.ipynb
/home/vikrant/trainings/2020/arcesium_finop_batch1_module1/.ipynb_checkpoints/day1-checkpoint.ipynb
/home/vikrant/trainings/2020/arcesium_finop_batch1_module1/.ipynb_checkpoints/day5-checkpoint.ipynb
/home/vikrant/trainings/2020/arcesium_finop_batch1_module1/.ipynb_checkpoints/day4-checkpoint.ipynb
/home/vikrant/trainings/2020/arcesium_finop_batch1_module1/.ipynb_checkpoints/day3-checkpoint.html
/home/vikrant/trainings/2020/arcesium_finop_batch1_module1/.ipynb_checkpoints/day2-checkpoint.ipynb
In [31]:
stocks = {"name":"IBM", "open":123, "high":125, "low":122, "close":123.5}
In [32]:
for item in stocks:
    print(item)
name
open
high
low
close
In [33]:
for key, value in stocks.items():
    print(key, value)
name IBM
open 123
high 125
low 122
close 123.5
In [34]:
for key in stocks:
    print(key, stocks[key])
name IBM
open 123
high 125
low 122
close 123.5
In [35]:
x, y = 2, 3
In [36]:
list(stocks.items())
Out[36]:
[('name', 'IBM'), ('open', 123), ('high', 125), ('low', 122), ('close', 123.5)]
In [37]:
for x, y in stocks.items():
    print(x, y)
name IBM
open 123
high 125
low 122
close 123.5
In [ ]:
for path, dirs, files in os.walk(os.getcwd()):
    for f in files
    

for x , y , z in os.walk(os.getcwd()):

problems

  1. write a function longlistdir which will print filenames and flolder names from given folder, such that before every file it prints a char f and before every directory it prints a character d
    >>> longlistdir(folderpath)
    d training
    f day1.html
    f day2.html
    d test
    f hello.py
  1. Write a fucntion findfiles which finds all files in given directory with given extension
    >>> findfiles("/var", "log")
    ['/var/log/alternative.log' ....]
  1. Write a function dirsize which will find size of dorectory in MB.
    >>> dirsize(os.getcwd())
    1.9
In [38]:
os.listdir()
Out[38]:
['day2.html',
 'day5.html',
 'push',
 'day2.ipynb',
 'day1.html',
 'day5.ipynb',
 'day3.html',
 'test',
 'day1.ipynb',
 'day4.html',
 'Makefile',
 '.ipynb_checkpoints',
 'day4.ipynb',
 'day3.ipynb']
In [42]:
os.path.isfile(os.path.join(os.getcwd(),"push")) # this checks if given path is file or directory
Out[42]:
True
In [43]:
os.path.isdir(os.path.join(cwd, "test"))
Out[43]:
True
In [45]:
os.path.isfile(os.path.join(cwd, "test"))
Out[45]:
False
In [48]:
def longlistdir(folder): # this is not recursive
    files = os.listdir(folder)
    for file in files:
        path = os.path.join(folder, file)
        if os.path.isfile(path):
            print("f", path)
        else:
            print("d", path)
In [49]:
longlistdir(cwd)
f /home/vikrant/trainings/2020/arcesium_finop_batch1_module1/day2.html
f /home/vikrant/trainings/2020/arcesium_finop_batch1_module1/day5.html
f /home/vikrant/trainings/2020/arcesium_finop_batch1_module1/push
f /home/vikrant/trainings/2020/arcesium_finop_batch1_module1/day2.ipynb
f /home/vikrant/trainings/2020/arcesium_finop_batch1_module1/day1.html
f /home/vikrant/trainings/2020/arcesium_finop_batch1_module1/day5.ipynb
f /home/vikrant/trainings/2020/arcesium_finop_batch1_module1/day3.html
d /home/vikrant/trainings/2020/arcesium_finop_batch1_module1/test
f /home/vikrant/trainings/2020/arcesium_finop_batch1_module1/day1.ipynb
f /home/vikrant/trainings/2020/arcesium_finop_batch1_module1/day4.html
f /home/vikrant/trainings/2020/arcesium_finop_batch1_module1/Makefile
d /home/vikrant/trainings/2020/arcesium_finop_batch1_module1/.ipynb_checkpoints
f /home/vikrant/trainings/2020/arcesium_finop_batch1_module1/day4.ipynb
f /home/vikrant/trainings/2020/arcesium_finop_batch1_module1/day3.ipynb
In [52]:
def longlistdir_(folder):
    for path, dirs, files in os.walk(folder):
        for f in files:
            print("f", os.path.join(path, f))
        for d in dirs:
            print("d", os.path.join(path, d))
In [53]:
longlistdir_(cwd)
f /home/vikrant/trainings/2020/arcesium_finop_batch1_module1/day2.html
f /home/vikrant/trainings/2020/arcesium_finop_batch1_module1/day5.html
f /home/vikrant/trainings/2020/arcesium_finop_batch1_module1/push
f /home/vikrant/trainings/2020/arcesium_finop_batch1_module1/day2.ipynb
f /home/vikrant/trainings/2020/arcesium_finop_batch1_module1/day1.html
f /home/vikrant/trainings/2020/arcesium_finop_batch1_module1/day5.ipynb
f /home/vikrant/trainings/2020/arcesium_finop_batch1_module1/day3.html
f /home/vikrant/trainings/2020/arcesium_finop_batch1_module1/day1.ipynb
f /home/vikrant/trainings/2020/arcesium_finop_batch1_module1/day4.html
f /home/vikrant/trainings/2020/arcesium_finop_batch1_module1/Makefile
f /home/vikrant/trainings/2020/arcesium_finop_batch1_module1/day4.ipynb
f /home/vikrant/trainings/2020/arcesium_finop_batch1_module1/day3.ipynb
d /home/vikrant/trainings/2020/arcesium_finop_batch1_module1/test
d /home/vikrant/trainings/2020/arcesium_finop_batch1_module1/.ipynb_checkpoints
f /home/vikrant/trainings/2020/arcesium_finop_batch1_module1/.ipynb_checkpoints/day1-checkpoint.html
f /home/vikrant/trainings/2020/arcesium_finop_batch1_module1/.ipynb_checkpoints/day3-checkpoint.ipynb
f /home/vikrant/trainings/2020/arcesium_finop_batch1_module1/.ipynb_checkpoints/day1-checkpoint.ipynb
f /home/vikrant/trainings/2020/arcesium_finop_batch1_module1/.ipynb_checkpoints/day5-checkpoint.ipynb
f /home/vikrant/trainings/2020/arcesium_finop_batch1_module1/.ipynb_checkpoints/day4-checkpoint.ipynb
f /home/vikrant/trainings/2020/arcesium_finop_batch1_module1/.ipynb_checkpoints/day3-checkpoint.html
f /home/vikrant/trainings/2020/arcesium_finop_batch1_module1/.ipynb_checkpoints/day2-checkpoint.ipynb
In [55]:
def print_list(items, path, start="f"):
    for item in items:
        print(start, os.path.join(path, item))

def longlistdir_(folder):
    for path, dirs, files in os.walk(folder):
        print_list(files, path)
        print_list(dirs, path, start="d")
In [56]:
longlistdir_(cwd)
f /home/vikrant/trainings/2020/arcesium_finop_batch1_module1/day2.html
f /home/vikrant/trainings/2020/arcesium_finop_batch1_module1/day5.html
f /home/vikrant/trainings/2020/arcesium_finop_batch1_module1/push
f /home/vikrant/trainings/2020/arcesium_finop_batch1_module1/day2.ipynb
f /home/vikrant/trainings/2020/arcesium_finop_batch1_module1/day1.html
f /home/vikrant/trainings/2020/arcesium_finop_batch1_module1/day5.ipynb
f /home/vikrant/trainings/2020/arcesium_finop_batch1_module1/day3.html
f /home/vikrant/trainings/2020/arcesium_finop_batch1_module1/day1.ipynb
f /home/vikrant/trainings/2020/arcesium_finop_batch1_module1/day4.html
f /home/vikrant/trainings/2020/arcesium_finop_batch1_module1/Makefile
f /home/vikrant/trainings/2020/arcesium_finop_batch1_module1/day4.ipynb
f /home/vikrant/trainings/2020/arcesium_finop_batch1_module1/day3.ipynb
d /home/vikrant/trainings/2020/arcesium_finop_batch1_module1/test
d /home/vikrant/trainings/2020/arcesium_finop_batch1_module1/.ipynb_checkpoints
f /home/vikrant/trainings/2020/arcesium_finop_batch1_module1/.ipynb_checkpoints/day1-checkpoint.html
f /home/vikrant/trainings/2020/arcesium_finop_batch1_module1/.ipynb_checkpoints/day3-checkpoint.ipynb
f /home/vikrant/trainings/2020/arcesium_finop_batch1_module1/.ipynb_checkpoints/day1-checkpoint.ipynb
f /home/vikrant/trainings/2020/arcesium_finop_batch1_module1/.ipynb_checkpoints/day5-checkpoint.ipynb
f /home/vikrant/trainings/2020/arcesium_finop_batch1_module1/.ipynb_checkpoints/day4-checkpoint.ipynb
f /home/vikrant/trainings/2020/arcesium_finop_batch1_module1/.ipynb_checkpoints/day3-checkpoint.html
f /home/vikrant/trainings/2020/arcesium_finop_batch1_module1/.ipynb_checkpoints/day2-checkpoint.ipynb
In [57]:
dir
Out[57]:
<function dir>
In [58]:
dir
Out[58]:
<function dir>
In [59]:
list
Out[59]:
list
In [61]:
dir_ ="a"
In [66]:
def findfiles(dirpath, ext="log"):
    search = []
    for path, dirs, files in os.walk(dirpath):
        for f in files:
            if f.endswith("." + ext):
                search.append(f)
                
    return search
In [72]:
findfiles("/home/vikrant/Downloads//",  "pdf")
Out[72]:
['RenewalPremium_9986696.pdf',
 'Cleartrip Hotel Voucher.pdf',
 'NITI-Directory041219.pdf',
 'All About Love_ New Visions.pdf',
 'Pippi Longstocking by Astrid Lindgren Lauren Child (illus) Tiina Nunnally (transl) (z-lib.org).pdf',
 'Fuelling_the_Transition-Report.pdf',
 'Data Visualisation- Session Plan.pdf',
 'UAM Workshop 4 & 5 October.pdf',
 'Adam (Marathi) by RATNAKAR MATKARI (z-lib.org).pdf',
 'TaxInvoiceMH1171811BU11822.pdf',
 '17.गहू .pdf',
 't480s_ug_en.pdf',
 '33861365_DOC1.pdf',
 'conda-cheatsheet.pdf',
 'Vikrant-profile (1).pdf',
 '000000001.pdf',
 'AccountStatement.pdf',
 'TaxInvoiceMH1181902CF09686.pdf',
 'BasicPythonPostAssessment-Solutions.pdf',
 'Invoice.pdf',
 "[Paul_Hoffman]_Archimedes'_Revenge__The_Joys_and_P(z-lib.org).pdf",
 'VIKRANT PATIL.pdf',
 'adventures_in_iterations (5).pdf',
 'De-mystifying AI_v2.pdf',
 'TaxInvoiceDL1181903CM65353.pdf',
 'intimacyinventory.pdf',
 'Manasollasa vol 2 pdf.pdf',
 'Ticket(s)_For_PyCon_India_2019.pdf',
 'Build Free- How to build your home with net-zero investment_AGP Version.pdf',
 'ibm-machine-learning-for-dummies-ibm-limited-edition_IMM14209USEN.pdf',
 '107577899-20190209.pdf',
 'TaxInvoiceAS1181903AK32800.pdf',
 '6326323_TDSInquiry.pdf',
 '9_MIDI_code.pdf',
 'GridPath.pdf',
 'Good-Will .pdf',
 '16. पिकलेला आंबा .pdf',
 'Vikrant-profile.pdf',
 'Emotional-Vocabulary-List-Color.pdf',
 'BasicPythonPostAssessment.pdf',
 'problem-solving-with-python.pdf',
 'Arcesium_FOP_Training_Modules.pdf',
 'W Template.pdf',
 'Invoice(1).pdf',
 'हनुमान ग्रामीण नगर पोलादपूर Containment zon आदेश क्र.246.pdf',
 '12918_0000406430.pdf',
 'InitiateSingleEntryPaymentSummaryUX510-04-2020.pdf',
 'Springer Ebooks.pdf',
 'Mastering Pandas for Finance.pdf',
 'Handbook_Final_WebVersion.pdf',
 'Corona Regulation Notification (Eng).pdf.pdf',
 'FHO_2017.pdf',
 '1927IA0200012877_signed.pdf',
 '161602_31_2019_12507.pdf',
 'Lele_Environment and Well Being_NLR 123_May June 2020.pdf',
 'ArtAtivitiesByAbhaBhagwat.pdf',
 'kutch-kutch-annsayre.pdf',
 'Paytm_Wallet_Txn_HistoryJun2019_8552969377.pdf',
 '12918_0000478298.pdf',
 '27061900049609.pdf',
 'InitiateSingleEntryPaymentSummaryUX512-06-2020.pdf',
 'Ragabot.pdf',
 'english_18.0.pdf',
 'Learning Web Concept Note V0.1  pdf.pdf',
 'numpy.pdf',
 'xml.pdf',
 'database.pdf']
In [76]:
x = 3**100
x
y = 2**100
y
Out[76]:
1267650600228229401496703205376
In [77]:
x = 3**100
print(x)
y = 2**100
print(y)
515377520732011331036461129765621272702107522001
1267650600228229401496703205376
In [81]:
def get_sizes(files, path):
    s = 0
    for f in files:
        filepath = os.path.join(path, f)
        s += os.path.getsize(filepath)
    return s

def dirsize(folderpath):
    s = 0 
    for path, dirs , files in os.walk(folderpath):
        s += get_sizes(files, path)
        s += get_sizes(dirs, path)
    return s/(1024*1024) # to make in MB
In [79]:
dirsize(cwd)
Out[79]:
2.815969467163086
In [80]:
dirsize("/home/vikrant/Downloads/")
Out[80]:
12627.826781272888
                    path                dirs                   files
+root               root                [folder1, folder4]   [f3.txt, f4.txt]
 |
 +--folder1         root/folder1        [folder]             [f1.txt, f2.txt]
 |  |
 |  +-- f1.txt
 |  +-- f2.txt
 |  +-- folder      root/folder/folder  []                   [x.txt]
 |      |
 |      +--- x.txt
 |
 +--f3.txt
 +--f4.txt
 +--folder4        root/folder4         []                   []

Writing custom modules

In [94]:
%%file stats.py
import math

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


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

def median(nums):
    n  = len(nums)
    c = n//2
    if n%2==0:
        return (numc[c]+num[c-1])/2
    else:
        return num[c]
Overwriting stats.py

Your own module is nothing but a text file with extenstion .py. Inside this file you write your releated python functions and data. This modue can be imported directly in python interpreter if the file is in current working directory. If it is not in current folder, then one has to add path of folder in which the file resides, to a system variable to PYTHONPATH.

In [95]:
import stats
In [90]:
stats.mean([1, 2, 3, 4, 5])
Out[90]:
3.0
In [91]:
stats.std([1, 2, 3,4 ,5 ,6])
Out[91]:
1.8708286933869707
In [92]:
stats.median([1, 2, 3, 4])
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-92-24306949a3db> in <module>
----> 1 stats.median([1, 2, 3, 4])

~/trainings/2020/arcesium_finop_batch1_module1/stats.py in median(nums)
     17     c = n//2
     18     if n%2==0:
---> 19         return (num[c]+num[c-1])/2
     20     else:
     21         return num[c]

NameError: name 'numc' is not defined
In [100]:
%%file stats2.py
import math

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


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

def median(nums):
    n  = len(nums)
    c = n//2
    if n%2==0:
        return (nums[c]+nums[c-1])/2
    else:
        return nums[c]
Writing stats2.py
In [101]:
import stats2
In [102]:
stats2.median([1, 2, 3, 4])
Out[102]:
2.5

python scripts

In [104]:
%%file hello.py

import sys

def hello(name):
    print("Hello", name + "!")
    
def welcome(name):
    hello(name)
    print("Welcome to python programming!")
    
name = sys.argv[1]

welcome(name)
Overwriting hello.py
In [105]:
!python3 hello.py vikrant
Hello vikrant!
Welcome to python programming!
In [106]:
%%file hello1.py

import sys

def hello(name):
    print("Hello", name + "!")
    
def welcome(name):
    hello(name)
    print("Welcome to python programming!")
   
print("sys.argv arguments -> ", sys.argv)
name = sys.argv[1]
welcome(name)
Writing hello1.py
In [107]:
!python3 hello1.py vikrant kfddf saghjg hgshjg khdfjgdsf 
sys.argv arguments ->  ['hello1.py', 'vikrant', 'kfddf', 'saghjg', 'hgshjg', 'khdfjgdsf']
Hello vikrant!
Welcome to python programming!
In [108]:
!python3 hello1.py vikrant
sys.argv arguments ->  ['hello1.py', 'vikrant']
Hello vikrant!
Welcome to python programming!
In [109]:
!python3 hello1.py vikrant 23 1.1 jkhdfj kdjhfkd
sys.argv arguments ->  ['hello1.py', 'vikrant', '23', '1.1', 'jkhdfj', 'kdjhfkd']
Hello vikrant!
Welcome to python programming!
In [110]:
%%file add.py
import sys

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


a = int(sys.argv[1])
b = int(sys.argv[2])

add(a, b)
    
Writing add.py
In [111]:
!python3 add.py 3 5
In [112]:
%%file add.py
import sys

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


a = int(sys.argv[1])
b = int(sys.argv[2])

print(add(a, b))
Overwriting add.py
In [115]:
!python3 add.py 343 4343
4686
In [114]:
import add
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-114-81459ef23ada> in <module>
----> 1 import add

~/trainings/2020/arcesium_finop_batch1_module1/add.py in <module>
      5 
      6 
----> 7 a = int(sys.argv[1])
      8 b = int(sys.argv[2])
      9 

ValueError: invalid literal for int() with base 10: '-f'
In [116]:
%%file add1.py
import sys

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


print(__name__)
a = int(sys.argv[1])
b = int(sys.argv[2])

print(add(a, b))
Writing add1.py
In [117]:
!python3 add1.py 34 23
__main__
57
In [118]:
import add1
add1
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-118-5ffa442179a0> in <module>
----> 1 import add1

~/trainings/2020/arcesium_finop_batch1_module1/add1.py in <module>
      6 
      7 print(__name__)
----> 8 a = int(sys.argv[1])
      9 b = int(sys.argv[2])
     10 

ValueError: invalid literal for int() with base 10: '-f'
In [126]:
%%file add2.py
import sys

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


print("__name__ = ", __name__)
if __name__ == "__main__":
    a = int(sys.argv[1])
    b = int(sys.argv[2])
    print(add(a, b))
Overwriting add2.py
In [132]:
!python3 add2.py 34 54 # when we run it as script, value of varianble __name__ -> "__main__"
__name__ =  __main__
88
In [128]:
import add2 ## when we import , value of variable __name__ -> module name
In [125]:
def hello():
    print("hello")
In [129]:
%%file add3.py
import sys

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


print("__name__ = ", __name__)
if __name__ == "__main__":
    a = int(sys.argv[1])
    b = int(sys.argv[2])
    print(add(a, b))
Writing add3.py
In [130]:
!python3 add3.py 34 54 
__name__ =  __main__
88
In [131]:
import add3
__name__ =  add3
In [ ]: