Python Virtual Training For Arcesium - Module I - Day 2¶

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-day2

notebook names are case sensitive. Make sure you give correct name

© Pipal Academy LLP

Functions¶

built-in functions. These functions are already there in python installtion

In [1]:
print("Hello World")
Hello World
In [2]:
len([1, 2, 3, 4])
Out[2]:
4
In [3]:
len((1, 2, 3, 4, 5))
Out[3]:
5
In [4]:
len("hello this is text")
Out[4]:
18
In [5]:
len("""one
two""")
Out[5]:
7
In [6]:
stock = {"ticker":"IBM", "value":125, "high":126, "low": 123}
In [7]:
len(stock)
Out[7]:
4
In [8]:
len({1, 2, 4, 3, 3, 3, 3, 3, 3})
Out[8]:
4
In [9]:
sum([1, 2, 3, 4])
Out[9]:
10
In [10]:
sum((1, 3, 4, 5))
Out[10]:
13
In [11]:
str(11) # will convert 11 into charecter '11'
Out[11]:
'11'
In [12]:
11
Out[12]:
11
In [13]:
int("123")
Out[13]:
123
In [15]:
x = input("Give value for x")
In [17]:
x # every input is always text! even if you give input as a number
Out[17]:
'555'
In [18]:
int(x)
Out[18]:
555
In [19]:
x * 3
Out[19]:
'555555555'
In [20]:
int(x)*3
Out[20]:
1665
In [22]:
x # this is string...interpreter response is showing '' around it
Out[22]:
'555'
In [23]:
print(x) # print does not show quotes
555
In [24]:
print(555)
555
In [25]:
print("555")
555
In [26]:
int(x) # is doing not changin x ... but it will make new int by using chars from x
Out[26]:
555
In [27]:
y = int(x)
In [28]:
type(y)
Out[28]:
int
In [29]:
type(x)
Out[29]:
str
In [30]:
int(x) # calling int on x does not change x
Out[30]:
555
In [31]:
stock
Out[31]:
{'ticker': 'IBM', 'value': 125, 'high': 126, 'low': 123}
In [32]:
stock['value'] = 126
In [33]:
stock
Out[33]:
{'ticker': 'IBM', 'value': 126, 'high': 126, 'low': 123}

basic data types (these are immutable)

  • int
  • float
  • string

higher level data types

  • tuple (immutable)
  • list (mutable)
  • dict (mutable)
  • set (mutable)
In [35]:
list("2323") # makes a list of chars
Out[35]:
['2', '3', '2', '3']
In [36]:
list((1, 2, 3, 4))
Out[36]:
[1, 2, 3, 4]
In [38]:
list(stock) # list of only keys 
Out[38]:
['ticker', 'value', 'high', 'low']
In [39]:
list({1, 1, 1, 2, 2, 3, 4})
Out[39]:
[1, 2, 3, 4]
In [40]:
names = ["Yash", "Akash", "Alice", "Alex"]
language = ["Hindi", "Telugu", "English", "Spanish"]
In [43]:
list(zip(names, language)) # nested function call!
Out[43]:
[('Yash', 'Hindi'),
 ('Akash', 'Telugu'),
 ('Alice', 'English'),
 ('Alex', 'Spanish')]
In [44]:
pairs = zip(names, language)
list(pairs)
Out[44]:
[('Yash', 'Hindi'),
 ('Akash', 'Telugu'),
 ('Alice', 'English'),
 ('Alex', 'Spanish')]
In [45]:
list(zip(names, language)) # innermost function will be called first. Then output of that will be passed as an argument to outer function
Out[45]:
[('Yash', 'Hindi'),
 ('Akash', 'Telugu'),
 ('Alice', 'English'),
 ('Alex', 'Spanish')]
In [47]:
print(1 + int(input("give integer"))) 
# input will be called first ..because it is inner most function
# then int will be called with the argument as output of input function
# 1 + output of int will be computed
# print will called with result as argument
7
In [50]:
dict([(1,"one"), (2,"two")])
Out[50]:
{1: 'one', 2: 'two'}
In [52]:
dict([[1,"one"], [2,"two"]]) # it will take first item from pair as  key and second item as value
Out[52]:
{1: 'one', 2: 'two'}
In [53]:
dict(zip(names, language))
Out[53]:
{'Yash': 'Hindi', 'Akash': 'Telugu', 'Alice': 'English', 'Alex': 'Spanish'}

We saw following built in functions

  • len
  • type
  • str
  • int
  • float
  • list
  • dict
  • zip
  • sum - sums the list/tuple of numbers
  • print
  • inut

problems

  1. Use python to find total income if the person has five sources of income each giving income 122335, 120000, 5444560, 112000, 55000

what data structure (higher level data type to store this data?) 2. Find out how many digits are there in 2$^3$$^2$ 3. Find out maximum income from above sources of income in problem 1 (there is a built in function called max/min which find max/min from a list/tuple..any sequence) 4. sum(["a", "b", "c", "d"]) will this work?

In [54]:
sum(1, 2, 3)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
Cell In[54], line 1
----> 1 sum(1, 2, 3)

TypeError: sum() takes at most 2 arguments (3 given)
In [55]:
sum([1, 2, 3])
Out[55]:
6
In [57]:
incomes = [122335, 120000, 5444560, 112000, 55000]
In [59]:
55 # it is integer
Out[59]:
55
In [60]:
'55'
Out[60]:
'55'
In [61]:
2**32
Out[61]:
4294967296
In [62]:
x = 10
y = 20
x = 30
In [63]:
sum = 54
In [64]:
sum
Out[64]:
54
In [66]:
sum([1, 2, 3, 4])
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
Cell In[66], line 1
----> 1 sum([1, 2, 3, 4])

TypeError: 'int' object is not callable
In [67]:
del sum 

getting back the built in

in case by mistake you named a variable same as built in function , then will not be able to the function unless you delete the variable

In [68]:
sum([1, 2, 3])
Out[68]:
6
In [72]:
str(2**32) # this converts integer into decimal digits as string chars
Out[72]:
'4294967296'
In [71]:
2**32 # internally integers/floats are stored in some binary representation. Here interpreter showing digits only for our convinience
Out[71]:
4294967296
In [73]:
len(str(2**32))
Out[73]:
10
In [74]:
0 + "a"
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
Cell In[74], line 1
----> 1 0 + "a"

TypeError: unsupported operand type(s) for +: 'int' and 'str'
In [75]:
["a", "b", "c", "d"]
0 + "a" 
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
Cell In[75], line 2
      1 ["a", "b", "c", "d"]
----> 2 0 + "a" 

TypeError: unsupported operand type(s) for +: 'int' and 'str'
In [76]:
["a", "b", "c", "d"]
"" + "a" 
Out[76]:
'a'
In [77]:
help(sum)
Help on built-in function sum in module builtins:

sum(iterable, /, start=0)
    Return the sum of a 'start' value (default: 0) plus an iterable of numbers
    
    When the iterable is empty, return the start value.
    This function is intended specifically for use with numeric values and may
    reject non-numeric types.

In [78]:
sum(["a", "b", "c", "d"], start="")
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
Cell In[78], line 1
----> 1 sum(["a", "b", "c", "d"], start="")

TypeError: sum() can't sum strings [use ''.join(seq) instead]

List slicing¶

  • When we want to access one item from a list we use simple indexing
  • When we want to access multiple items from a list at a time we use slicing
In [80]:
list(range(10))
Out[80]:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
In [81]:
digits = list(range(10))
In [82]:
digits
Out[82]:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
In [84]:
len(digits)
Out[84]:
10
In [83]:
digits[0] # zeroth element
Out[83]:
0
In [85]:
digits[2:6] # give elements from index 2 till index 5 (exclide 6)
Out[85]:
[2, 3, 4, 5]
In [86]:
digits[:5] # take first five
Out[86]:
[0, 1, 2, 3, 4]
In [88]:
digits[3:] # drop first three
Out[88]:
[3, 4, 5, 6, 7, 8, 9]
In [90]:
digits[2:9:2] # start at index 2 go till 8 (exlude 9) and at step of 2
Out[90]:
[2, 4, 6, 8]
In [91]:
digits[2::2]
Out[91]:
[2, 4, 6, 8]
In [92]:
first_100 = list(range(100))
In [96]:
first_100[:5] # head 
Out[96]:
[0, 1, 2, 3, 4]
In [97]:
first_100[-5:] # tail
Out[97]:
[95, 96, 97, 98, 99]
In [99]:
sum(first_100[2::2])
Out[99]:
2450

most generic format of list slicing is

items[start:end:step]
anything not given is taken as default
start is not given then start is taken 0
end is not given then end is taken as end of list
step is not given then step is taken as 1
In [100]:
[1, 2, 3, 4]
Out[100]:
[1, 2, 3, 4]
In [101]:
[1, 2, 3, 4]*20
Out[101]:
[1,
 2,
 3,
 4,
 1,
 2,
 3,
 4,
 1,
 2,
 3,
 4,
 1,
 2,
 3,
 4,
 1,
 2,
 3,
 4,
 1,
 2,
 3,
 4,
 1,
 2,
 3,
 4,
 1,
 2,
 3,
 4,
 1,
 2,
 3,
 4,
 1,
 2,
 3,
 4,
 1,
 2,
 3,
 4,
 1,
 2,
 3,
 4,
 1,
 2,
 3,
 4,
 1,
 2,
 3,
 4,
 1,
 2,
 3,
 4,
 1,
 2,
 3,
 4,
 1,
 2,
 3,
 4,
 1,
 2,
 3,
 4,
 1,
 2,
 3,
 4,
 1,
 2,
 3,
 4]
In [102]:
"[1, 2, 3, 4, 5]" # this is not a list it is just text with some chars in it
Out[102]:
'[1, 2, 3, 4, 5]'
In [103]:
list("[1, 2, 3, 4, 5]")
Out[103]:
['[', '1', ',', ' ', '2', ',', ' ', '3', ',', ' ', '4', ',', ' ', '5', ']']
In [104]:
x = 10
y = 20
z = 30
m = 45
n = 5
[x, y, z, m, n]
Out[104]:
[10, 20, 30, 45, 5]
In [105]:
11111
Out[105]:
11111
In [106]:
digits[::] # copy
Out[106]:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
In [107]:
digits[::-1] # reverse
Out[107]:
[9, 8, 7, 6, 5, 4, 3, 2, 1, 0]

slicing also works for strings¶

In [108]:
text = "This is some text data to work with slicing"
In [109]:
text[5:] # drop first five
Out[109]:
'is some text data to work with slicing'
In [110]:
text[:5] # take first five chars
Out[110]:
'This '
In [111]:
text[-5:] # take last five char
Out[111]:
'icing'
In [112]:
text[:-5] # take everyting except last 5
Out[112]:
'This is some text data to work with sl'
In [113]:
text[::-1] # reverse
Out[113]:
'gnicils htiw krow ot atad txet emos si sihT'
In [119]:
del x # del is a statement, after this you give space and variable name you want to delete
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
Cell In[119], line 1
----> 1 del x # del is a statement, after this you give space and variable name you want to delete

NameError: name 'x' is not defined

Writing your own functions¶

In [116]:
complex_list = [[1, 2, 3], ["one", "two", "three"]]
index = 1
numeric, text = complex_list[0][index], complex_list[1][index]
print(numeric, text)
2 two
In [117]:
add
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
Cell In[117], line 1
----> 1 add

NameError: name 'add' is not defined
In [122]:
def add(a, b): # don't miss this colon
    return a + b # body function should be indented by 4 spaces (convention)
In [123]:
add
Out[123]:
<function __main__.add(a, b)>
In [124]:
add(2, 3)
Out[124]:
5
In [125]:
complex_list = [[1, 2, 3], ["one", "two", "three"]]
index = 0
numeric, text = complex_list[0][index], complex_list[1][index]
print(numeric, text)
1 one
In [126]:
complex_list = [[1, 2, 3], ["one", "two", "three"]]
index = 1
numeric, text = complex_list[0][index], complex_list[1][index]
print(numeric, text)
2 two
In [127]:
def get_pair_from_complex_list(pair_list, index):
    return pair_list[0][index], pair_list[1][index] # it will return two items at a time as tuple
In [128]:
get_pair_from_complex_list(complex_list, 0)
Out[128]:
(1, 'one')
In [129]:
get_pair_from_complex_list(complex_list, 1)
Out[129]:
(2, 'two')
In [130]:
get_pair_from_complex_list(complex_list, 2)
Out[130]:
(3, 'three')
In [132]:
def square(a):
    return a*a

def sumofsquares(x, y):
 x_2 = square(x)
    y_2 = square(y)
    return x_2 + y_2
  Cell In[132], line 6
    y_2 = square(y)
    ^
IndentationError: unexpected indent
In [133]:
def square(a):
    return a*a

def sumofsquares(x, y):
    x_2 = square(x)
    y_2 = square(y)
    
return x_2 + y_2
  Cell In[133], line 8
    return x_2 + y_2
    ^
SyntaxError: 'return' outside function
In [134]:
return 5
  Cell In[134], line 1
    return 5
    ^
SyntaxError: 'return' outside function
In [135]:
def square(a):
    return a*a

def sumofsquares(x, y):
    x_2 = square(x)
    y_2 = square(y)
    return x_2 + y_2
In [136]:
sumofsquares(5, 6)
Out[136]:
61
In [137]:
def print_double(x):
    print(2*x)
In [139]:
print_double(3) # but this is a print not return!
6
In [140]:
x = print_double(5)
10
In [141]:
print(x)
None
In [142]:
s = sumofsquares(5, 7)
In [143]:
print(s)
74
In [144]:
def double1(x):
    2*x 
In [145]:
double1(5)
  • sumofsquares - returns a value
  • print_double - just prints a value but does not return
  • double1 - just computes ..but does not return and does not even print

Function names can be just like variable names

  • The function name can't start with number
  • it can be a single word (it can not have space, hyphen, comma, any operator)
  • it can have alphapbets, numbers and underscore
  • Always try to give names to functions and variables such that it is understandable what it is doing
In [146]:
def add(2, 3): # incorrect, it should be variable name
    return 2 +3 

def add("a", "b"): # incorrect, it should be variable and not a literal
    return a + b
  Cell In[146], line 1
    def add(2, 3): # incorrect, it should be variable name
            ^
SyntaxError: invalid syntax
In [147]:
add(2, 3)
Out[147]:
5
In [148]:
x = 56
y = 47
add(x, y)
Out[148]:
103
In [149]:
def mysum(*args): # this means any number of arguments
    return sum(args)
In [150]:
mysum(1, 2, 3, 4)
Out[150]:
10
In [151]:
mysum(1, 2)
Out[151]:
3
In [152]:
def simple_interest(P, N=5, R=5.5): # default args
    return P*N*R/100
In [153]:
simple_interest(5000)
Out[153]:
1375.0
In [154]:
simple_interest(10000)
Out[154]:
2750.0
In [155]:
simple_interest(10000, N=10, R=6)
Out[155]:
6000.0
In [156]:
simple_interest(10000,10,6)
Out[156]:
6000.0
In [162]:
def print_double(x):
    print(2*x) # is printing but not returning
               # if function does not return anything it reurns None
In [161]:
print(print_double(5)) # None is coming from outside print statement and 10 is coming from print inside print_double function
10
None
In [158]:
print_double(5) # this is not returning 10! it is
10
In [159]:
x = print_double(5)
10
In [160]:
print(x)
None
In [165]:
def foo(x):
    x**2 # if there is not return statement , function will return None on its own...
In [166]:
foo(4)
In [167]:
print(foo(4))
None
In [ ]: