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

Jun 20-24, 2022 Vikrant Patil

All notes are available online at https://notes.pipal.in/2022/arcesium_finop_batch1/

Please accept the invitation that you have received in your email and login to

https://engage.pipal.in/

© Pipal Academy LLP

Problem set Day3¶

In [1]:
#"(3465324.54)" -> -13465324.54

def numeric_value(text_num):
    x = text_num.replace("(", "-").replace(")", "")
    return float(x)
In [2]:
numeric_value("(2323.6")
Out[2]:
-2323.6
In [3]:
numeric_value("5656.6") #
Out[3]:
5656.6
In [4]:
text = "hello this is what it is!"
In [5]:
text.replace("how", "where")
Out[5]:
'hello this is what it is!'
In [7]:
def reverse_digits(integer):
    reversed_ = str(integer)[::-1]
    return int(reversed_)

reverse_digits(3435435)
pass # this is empty statement
In [9]:
def reverse_digits(integer):
    reversed_ = str(integer)[::-1]
    return int(reversed_)

print(reverse_digits(3435435))
5345343
In [10]:
'3435435'[::-1]
Out[10]:
'5345343'
In [11]:
int('5345343')
Out[11]:
5345343
In [12]:
num = 34343
In [13]:
list(3434) 
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
Input In [13], in <cell line: 1>()
----> 1 list(3434)

TypeError: 'int' object is not iterable
In [14]:
list('34343')
Out[14]:
['3', '4', '3', '4', '3']
In [15]:
num
Out[15]:
34343
In [17]:
num[::-1] # slicing is only for collections like list, str, tuple
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
Input In [17], in <cell line: 1>()
----> 1 num[::-1]

TypeError: 'int' object is not subscriptable
In [18]:
def digit_count(number, digit):
    return str(number).count(str(digit))


def digit_count(number, digit):
    strnum = str(number)
    strdigit = str(digit)
    return strnum.count(strdigit)
In [30]:
def test_reverse_digits():
    assert reverse_digits(1234) == 4321
    assert reverse_digits(1) == 1
    assert reverse_digits(0) == 0
In [31]:
test_reverse_digits() # everything passed!
In [22]:
def test_reverse_digits1():
    assert reverse_digits1(1234) == 4321
In [26]:
def reverse_digits1(num):
    return str(num)[::-1]
In [28]:
reverse_digits1(1234)
Out[28]:
'4321'
In [29]:
test_reverse_digits1()
---------------------------------------------------------------------------
AssertionError                            Traceback (most recent call last)
Input In [29], in <cell line: 1>()
----> 1 test_reverse_digits1()

Input In [22], in test_reverse_digits1()
      1 def test_reverse_digits1():
----> 2     assert reverse_digits1(1234) == 4321

AssertionError: 
In [38]:
#def mean(nums):
#    return sum(nums)/len(nums)


def mean(nums):
    return (nums[0]+nums[1]+nums[2]+nums[3]+nums[4])/5

def test_mean():
    assert mean([1,2,3,4,5]) == 3.0
    assert mean([1,2]) == 1.5
    assert mean(range(1,10)) == 5.5
In [39]:
test_mean()
---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
Input In [39], in <cell line: 1>()
----> 1 test_mean()

Input In [38], in test_mean()
      8 def test_mean():
      9     assert mean([1,2,3,4,5]) == 3.0
---> 10     assert mean([1,2]) == 1.5
     11     assert mean(range(1,10)) == 5.5

Input In [38], in mean(nums)
      5 def mean(nums):
----> 6     return (nums[0]+nums[1]+nums[2]+nums[3]+nums[4])/5

IndexError: list index out of range
In [40]:
1 == 2
Out[40]:
False
In [41]:
2 == 1
Out[41]:
False
In [42]:
1 == 1
Out[42]:
True
In [43]:
two = [1,2]
In [44]:
two[2]
---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
Input In [44], in <cell line: 1>()
----> 1 two[2]

IndexError: list index out of range
In [46]:
nums = [1, 2, 3, 4, 5]
In [47]:
nums[2]
Out[47]:
3
In [49]:
num = 2232
In [50]:
num[2]
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
Input In [50], in <cell line: 1>()
----> 1 num[2]

TypeError: 'int' object is not subscriptable

Styleguide for writing functions¶

In [51]:
def twice(x):
    print(2*x)
In [52]:
fourtimes5 = twice(twice(5)) # this will fail
10
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
Input In [52], in <cell line: 1>()
----> 1 fourtimes5 = twice(twice(5))

Input In [51], in twice(x)
      1 def twice(x):
----> 2     print(2*x)

TypeError: unsupported operand type(s) for *: 'int' and 'NoneType'
In [53]:
def twice(x):
    return 2*x
In [56]:
twice(twice(5)) # this jupyter interpreter. this automatically shows me output of last like in this code cell
Out[56]:
20
In [58]:
twice(twice(5)) # this executed but no results are shown because this is last line in this cell
pass # empty statement
In [55]:
twice(twice(twice(5)))
Out[55]:
40
In [59]:
a, b = 1, 2

def add_():
    return a+b # this not recommeded way of writing code!

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

    
In [60]:
add(3, 5)
Out[60]:
8
In [61]:
add(1000, 454609)
Out[61]:
455609
In [63]:
add_() # just computes a+b! 
Out[63]:
3
In [64]:
n = 3
def power(x):
    return x**n # not a good way!
In [66]:
def cube(x):
    return x**3
In [67]:
def power(base, exponent):
    return base**exponent

recap methods from list¶

In [68]:
ones = [1, 1, 1, 1]
In [69]:
ones.append(2)
In [70]:
[1, 2, 3, 4] + [0]
Out[70]:
[1, 2, 3, 4, 0]
In [71]:
xlist = [1, 1, 1]

def appendzero(ylist):
    ylist = ylist + [0] # this creates a local variable!
    
appendzero(xlist) # here xlist is linked with ylist...they point to same object
print(xlist)
[1, 1, 1]
In [72]:
xlist = [1, 1, 1]

def appendzero(ylist):
    ylist.append(0) # list method
    
appendzero(xlist)
print(xlist)
[1, 1, 1, 0]
In [73]:
zlist = [1, 2, 3, 4,5]

appendzero(zlist)
print(zlist)
[1, 2, 3, 4, 5, 0]

Functions Arguments¶

In [74]:
def cylinder_volume(radius, height):
    return 3.14*radius**2*height
In [75]:
cylinder_volume(1, 2) # positinal arguments... order is important
Out[75]:
6.28
In [77]:
cylinder_volume(2, 1) # by mistake I changed order of arguments, so you get wrong results
Out[77]:
12.56
In [83]:
cylinder_volume(height=2, radius=1) # if i give named arguments..then order does not matter
Out[83]:
6.28
In [84]:
def foo(a, b, c, d):
    return ((a**b)*c)+d
In [85]:
foo(1, 2, 3, 4)
Out[85]:
7
In [86]:
foo(2, 1, 3, 4)
Out[86]:
10
In [87]:
foo(1, c=3, d=4, b=2) # you can give first few arguments without name..but in correct order
Out[87]:
7
In [89]:
foo(c=3, d=4, 1, 2) # this is not allowed... positional argument can not follow named argument
  Input In [89]
    foo(c=3, d=4, 1, 2) # this is not allowed... positional argument can not follow named argument
                      ^
SyntaxError: positional argument follows keyword argument
In [90]:
foo(1, 2, 3, d=4) # named arguments can follow positional argument
Out[90]:
7
In [91]:
def say_hello(name, greeting):
    print(name, greeting)
In [92]:
def say_hello(name, greeting="hello"): # default argument!
    print(name, greeting)
In [93]:
say_hello("vikrant") # if you don't give greeting argument.. it will take default value
vikrant hello
In [94]:
say_hello("vikrant", "welcome")
vikrant welcome
In [95]:
say_hello(name="vikrant", greeting="welcome")
vikrant welcome
In [96]:
def say_hello(name):
    print(name,"hello")
In [97]:
def say_welcome(name):
    print(name,"welcome")
In [99]:
def greetings(name, greetingtype="Hello"):
    print(greetingtype, name)
In [100]:
greetings("vikrant")
Hello vikrant
In [101]:
greetings("vikrant", "Welcome")
Welcome vikrant

Passing Functions as Arguments¶

In [102]:
def foobar():
    print("foobar")
In [103]:
foobar
Out[103]:
<function __main__.foobar()>
In [104]:
print(foobar)
<function foobar at 0x7f50f6cee170>
In [105]:
print(3)
3
In [106]:
print(foobar)
<function foobar at 0x7f50f6cee170>
In [108]:
def sqaure(x):
    return x*x


def sumofsquares(x, y):
    return sqaure(x) + sqaure(y) # in your new functions you call all your old functions or you can anyway call built in functions


def cube(x):
    return x**3


def sumofcubes(x, y):
    return cube(x) + cube(y)
In [109]:
sumofsquares(2, 3)
Out[109]:
13
In [110]:
sumofcubes(4, 5)
Out[110]:
189
In [111]:
def sumof(x, y, func):
    return func(x) + func(y)
In [112]:
sumof(4, 5, cube)
Out[112]:
189
In [113]:
sumof(2, 3, sqaure)
Out[113]:
13
In [114]:
max([3, 232, 434, 56])
Out[114]:
434
In [115]:
def foosum(x, y, funcx, funcy):
    return funcx(x), funcy(y)
In [117]:
foosum(5, 7, sqaure, cube)
Out[117]:
(25, 343)
In [122]:
def foosum(x,funcx, y, funcy):
    return funcx(x)+ funcy(y)
In [123]:
foosum(5, cube, 10, sqaure)
Out[123]:
225
In [124]:
abs(-1)
Out[124]:
1
In [125]:
foosum(-5, abs, 4, sqaure)
Out[125]:
21
In [126]:
max([324, 3434, 455, 65])
Out[126]:
3434
In [127]:
help(max)
Help on built-in function max in module builtins:

max(...)
    max(iterable, *[, default=obj, key=func]) -> value
    max(arg1, arg2, *args, *[, key=func]) -> value
    
    With a single iterable argument, return its biggest item. The
    default keyword-only argument specifies an object to return if
    the provided iterable is empty.
    With two or more arguments, return the largest argument.

In [128]:
words = ["one", "two", "three", "four", "five", "six", "seven"]
In [130]:
max(words) # take alphabetical order.. dictinary order and return last item
Out[130]:
'two'
In [131]:
max(words, key=len)
Out[131]:
'three'
In [136]:
def mylen(word):
    print("processing", word, ", it has length:", len(word))
    return len(word)
In [137]:
mylen("xyz")
processing xyz , it has length: 3
Out[137]:
3
In [138]:
words
Out[138]:
['one', 'two', 'three', 'four', 'five', 'six', 'seven']
In [139]:
max(words, key=mylen)
processing one , it has length: 3
processing two , it has length: 3
processing three , it has length: 5
processing four , it has length: 4
processing five , it has length: 4
processing six , it has length: 3
processing seven , it has length: 5
Out[139]:
'three'
In [140]:
words_ = ['one', 'seven', 'two', 'three', 'four', 'five', 'six']
max(words_, key=mylen)
processing one , it has length: 3
processing seven , it has length: 5
processing two , it has length: 3
processing three , it has length: 5
processing four , it has length: 4
processing five , it has length: 4
processing six , it has length: 3
Out[140]:
'seven'
In [141]:
def fixed_value(x):
    return 3
In [142]:
max(words, key=fixed_value) 
Out[142]:
'one'
In [143]:
words_ = ['one', 'seven', 'two', 'three', 'four', 'five', 'six']
max(words_, key=mylen) # max can bring up only one values.. so if their is a tie then first occurence will be returned
processing one , it has length: 3
processing seven , it has length: 5
processing two , it has length: 3
processing three , it has length: 5
processing four , it has length: 4
processing five , it has length: 4
processing six , it has length: 3
Out[143]:
'seven'

Suppose There are some records which name, value and gain

In [144]:
records = [
    ("TATA", 200.0, 5.5),
    ("INFY", 2000.0, -5),
    ("RELIANCE",1505.5, 50),
    ("HCL",1200, 70.5)]
In [145]:
records
Out[145]:
[('TATA', 200.0, 5.5),
 ('INFY', 2000.0, -5),
 ('RELIANCE', 1505.5, 50),
 ('HCL', 1200, 70.5)]
In [146]:
records[0]
Out[146]:
('TATA', 200.0, 5.5)
In [147]:
records[-1]
Out[147]:
('HCL', 1200, 70.5)
In [148]:
def get_value(record):
    return record[1]

def get_name(record):
    return record[0]

def get_gain(record):
    return record[2]
In [149]:
get_value(records[0])
Out[149]:
200.0
In [152]:
max(records, key=get_value) # row with max value
Out[152]:
('INFY', 2000.0, -5)
In [153]:
records
Out[153]:
[('TATA', 200.0, 5.5),
 ('INFY', 2000.0, -5),
 ('RELIANCE', 1505.5, 50),
 ('HCL', 1200, 70.5)]
In [154]:
max(records, key=get_gain)
Out[154]:
('HCL', 1200, 70.5)
In [155]:
min(records, key=get_value)
Out[155]:
('TATA', 200.0, 5.5)
In [156]:
min(records, key=get_gain)
Out[156]:
('INFY', 2000.0, -5)
In [157]:
sorted([2133, 43, 45, 654, 6])
Out[157]:
[6, 43, 45, 654, 2133]
In [158]:
sorted(records, key=get_value)
Out[158]:
[('TATA', 200.0, 5.5),
 ('HCL', 1200, 70.5),
 ('RELIANCE', 1505.5, 50),
 ('INFY', 2000.0, -5)]
In [159]:
records
Out[159]:
[('TATA', 200.0, 5.5),
 ('INFY', 2000.0, -5),
 ('RELIANCE', 1505.5, 50),
 ('HCL', 1200, 70.5)]
In [167]:
nums = [1,2, 34, 23, 5, 2, 4]
In [168]:
sorted(nums) # a new sorted list is returned
Out[168]:
[1, 2, 2, 4, 5, 23, 34]
In [169]:
nums
Out[169]:
[1, 2, 34, 23, 5, 2, 4]
In [170]:
nums.sort() # method! it changes orignal data
In [171]:
nums
Out[171]:
[1, 2, 2, 4, 5, 23, 34]
In [173]:
sorted(records, key=get_value,reverse=True)
Out[173]:
[('INFY', 2000.0, -5),
 ('RELIANCE', 1505.5, 50),
 ('HCL', 1200, 70.5),
 ('TATA', 200.0, 5.5)]

problem using max and key function can you find out a record of a company who has longest name

In [174]:
def get_name_len(r):
    name = get_name(r)
    return len(name)
In [175]:
max(records, key=get_name_len)
Out[175]:
('RELIANCE', 1505.5, 50)

Conditions¶

In [176]:
True
Out[176]:
True
In [177]:
False
Out[177]:
False
In [178]:
"hel" in "hello"  # check if string hel is in hello or not!
Out[178]:
True
In [179]:
name = "vikrant"
fullname = "vikrant patil"
In [180]:
name in fullname
Out[180]:
True
In [181]:
fullname in name
Out[181]:
False
In [182]:
fullname not in name
Out[182]:
True
In [183]:
"bel" in "hello"
Out[183]:
False
In [184]:
"bel" not in "hello"
Out[184]:
True
In [185]:
nums
Out[185]:
[1, 2, 2, 4, 5, 23, 34]
In [186]:
0 in nums
Out[186]:
False
In [187]:
1 in nums
Out[187]:
True
In [188]:
t = (0, 1, 2, 3, 45, 5)
In [189]:
-1 in t
Out[189]:
False
In [190]:
5 in t
Out[190]:
True
In [192]:
scores ={"vikrant":42, "vendant":45, "vrushali":50}
In [194]:
"vikrant" in scores  # it will in keys!
Out[194]:
True
In [195]:
50 in scores.values()
Out[195]:
True
In [196]:
55 in scores.values()
Out[196]:
False
In [197]:
"abhishek" in scores # it will check on keys
Out[197]:
False
In [198]:
50 in scores # it wil try to search 50 in keys...so it will fail
Out[198]:
False
In [200]:
scores.values() # it is some kind of collection
Out[200]:
dict_values([42, 45, 50])
In [201]:
x, y = 5, 6
In [202]:
x > y
Out[202]:
False
In [203]:
x >= y
Out[203]:
False
In [205]:
x == y # true if equal
Out[205]:
False
In [206]:
x != y # true if not equal
Out[206]:
True
In [207]:
if "hel" in "hello":
    print("hel!")
    print("blah, blah")
elif "cel" in "hell":
    print("cell!")
elif "del" in "bell":
    print("dell")
else:
    print("oops!")
hel!
blah, blah
In [208]:
x , y = 3, 3
if x == y and y != 0:
    print(x/y)
1.0
In [209]:
x , y = 0, 0
if x == y and y != 0:
    print(x/y)
In [210]:
x , y = 0, 0
if x == y and y != 0:
    print(x/y)
else:
    print("condition not satified")
condition not satified
In [211]:
x , y = 3, 4
if x == y or y > 0:
    print(x/y)
else:
    print("condition not satified")
0.75

cond1 and cond2 or cond3 this we can add multiple conditions together

cond1 and (cond2 or cond3)

Loops¶

To iterate over a collection in python you don't need keep track of index! for every_student in class this is how python for loop looks, just like plain english

In [217]:
multiline = """Navya Raj
Gosala Rajeshwari  Nidhi
Roychoudhury, Nayana
Ankit Singh
Mittal, Anirudh
Umang Bansal
Shreya Bansal
Himanshu Agarwal
Manav Malhotra
Abhishek Mathur
Abhishek Singh
Chillara Harsha Vardhan
Padamata venkata satyanarayana
Darshil Patel
Snigdha Damaraju
Sakshi Jain
Santosh Kumar
Shyam Kumar Ramasubramanian
Nikhil Menon
Sachin Jaiswal""".replace(",","")
In [218]:
classroom = multiline.split("\n") # split on newline
In [219]:
classroom
Out[219]:
['Navya Raj',
 'Gosala Rajeshwari  Nidhi',
 'Roychoudhury Nayana',
 'Ankit Singh',
 'Mittal Anirudh',
 'Umang Bansal',
 'Shreya Bansal',
 'Himanshu Agarwal',
 'Manav Malhotra',
 'Abhishek Mathur',
 'Abhishek Singh',
 'Chillara Harsha Vardhan',
 'Padamata venkata satyanarayana',
 'Darshil Patel',
 'Snigdha Damaraju',
 'Sakshi Jain',
 'Santosh Kumar',
 'Shyam Kumar Ramasubramanian',
 'Nikhil Menon',
 'Sachin Jaiswal']
In [223]:
def solve_some_problems(student):
    print(student, ":", "Yes, I have done it")
In [227]:
for student in classroom: # student is iteration variable created during this for loop which can be used inside for body
    solve_some_problems(student)
    pass
    pass
    pass
    print("*"*10) # till this it is body of for loop
    
print("This is outside for loop")
Navya Raj : Yes, I have done it
**********
Gosala Rajeshwari  Nidhi : Yes, I have done it
**********
Roychoudhury Nayana : Yes, I have done it
**********
Ankit Singh : Yes, I have done it
**********
Mittal Anirudh : Yes, I have done it
**********
Umang Bansal : Yes, I have done it
**********
Shreya Bansal : Yes, I have done it
**********
Himanshu Agarwal : Yes, I have done it
**********
Manav Malhotra : Yes, I have done it
**********
Abhishek Mathur : Yes, I have done it
**********
Abhishek Singh : Yes, I have done it
**********
Chillara Harsha Vardhan : Yes, I have done it
**********
Padamata venkata satyanarayana : Yes, I have done it
**********
Darshil Patel : Yes, I have done it
**********
Snigdha Damaraju : Yes, I have done it
**********
Sakshi Jain : Yes, I have done it
**********
Santosh Kumar : Yes, I have done it
**********
Shyam Kumar Ramasubramanian : Yes, I have done it
**********
Nikhil Menon : Yes, I have done it
**********
Sachin Jaiswal : Yes, I have done it
**********
This is outside for loop
In [226]:
words
Out[226]:
['one', 'two', 'three', 'four', 'five', 'six', 'seven']
In [229]:
for word in words: # name of iteration variable is your choice... but give meaningfull name so that it reads like english
    print(word, ":", len(word))
one : 3
two : 3
three : 5
four : 4
five : 4
six : 3
seven : 5
In [231]:
for char in "some text data":
    print(char, end=",") # after every print dont add newline but add comma
s,o,m,e, ,t,e,x,t, ,d,a,t,a,
In [232]:
scores
Out[232]:
{'vikrant': 42, 'vendant': 45, 'vrushali': 50}
In [234]:
for key in scores: # loops over keys
    print(key)
vikrant
vendant
vrushali
In [235]:
for student in classroom[:5]: # take only first 5
    print(student)
Navya Raj
Gosala Rajeshwari  Nidhi
Roychoudhury Nayana
Ankit Singh
Mittal Anirudh
In [237]:
for student in classroom[2:]: # drop first two students, but go over remaining
    print(student)
Roychoudhury Nayana
Ankit Singh
Mittal Anirudh
Umang Bansal
Shreya Bansal
Himanshu Agarwal
Manav Malhotra
Abhishek Mathur
Abhishek Singh
Chillara Harsha Vardhan
Padamata venkata satyanarayana
Darshil Patel
Snigdha Damaraju
Sakshi Jain
Santosh Kumar
Shyam Kumar Ramasubramanian
Nikhil Menon
Sachin Jaiswal
In [238]:
nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
In [240]:
for n in nums[::2]: #take alternate number
    print(n, end=",")
1,3,5,7,9,
In [257]:
for key in scores: # loops over keys
    print(key)
vikrant
vendant
vrushali
In [258]:
for key, value in scores.items(): # loops over keys and values
    print(key, value)
vikrant 42
vendant 45
vrushali 50
In [244]:
for score in scores.values():
    print(score)
42
45
50
In [246]:
scores.items()
Out[246]:
dict_items([('vikrant', 42), ('vendant', 45), ('vrushali', 50)])
In [247]:
records
Out[247]:
[('TATA', 200.0, 5.5),
 ('INFY', 2000.0, -5),
 ('RELIANCE', 1505.5, 50),
 ('HCL', 1200, 70.5)]
In [248]:
for record in records:
    print(record)
('TATA', 200.0, 5.5)
('INFY', 2000.0, -5)
('RELIANCE', 1505.5, 50)
('HCL', 1200, 70.5)
In [249]:
for name, value, gain in records:
    print(name, value, gain)
TATA 200.0 5.5
INFY 2000.0 -5
RELIANCE 1505.5 50
HCL 1200 70.5
In [253]:
scores.items() # only for dictianries
Out[253]:
dict_items([('vikrant', 42), ('vendant', 45), ('vrushali', 50)])
In [254]:
for name, score in scores.items(): # it will give items in the order by which dictionary has stored it
    print(name, score)
vikrant 42
vendant 45
vrushali 50
In [259]:
matrix = [[1, 2, 3],[4, 5, 6], [7,8, 9]]
In [260]:
for col1, col2, col3 in matrix:
    print(col1, col2, col3)
1 2 3
4 5 6
7 8 9
In [262]:
for row in matrix: # because every row has 3 items in it I can put three variable as iteration variables as above
    print(row)
[1, 2, 3]
[4, 5, 6]
[7, 8, 9]

Example¶

In [283]:
def mysum(nums):
    """This computes sum of numbers
    """
    
    s = 0 # usual practice in accumulation ..zero because it is unaffected by addition
    for n in nums:
        s =  s + n
    return s
In [264]:
nums
Out[264]:
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
In [265]:
mysum(nums)
Out[265]:
55
In [266]:
for i in range(10):
    print(i, end=",")
0,1,2,3,4,5,6,7,8,9,
In [267]:
mysum(range(1, 101))
Out[267]:
5050
In [269]:
mysum(range(1, 11))
Out[269]:
55
In [279]:
def product(nums):
    """computes product of all numbers from a list
    """
    p = 1
    for n in nums:
        p = p * n
    return p
In [275]:
product(nums)
Out[275]:
3628800
In [276]:
product([2, 3, 4])
Out[276]:
24
In [277]:
help(product)
Help on function product in module __main__:

product(nums)
    computes product of all numbers from a list

In [278]:
help(mysum)
Help on function mysum in module __main__:

mysum(nums)
    This computes sum of numbers

In [281]:
def mysum_(nums):
    """This computes sum of numbers
    """
    
    #s = 0 # usual practice in accumulation ..zero because 
    for n in nums:
        s =  s + n
    return s
In [282]:
mysum_(range(5))
---------------------------------------------------------------------------
UnboundLocalError                         Traceback (most recent call last)
Input In [282], in <cell line: 1>()
----> 1 mysum_(range(5))

Input In [281], in mysum_(nums)
      5 #s = 0 # usual practice in accumulation ..zero because 
      6 for n in nums:
----> 7     s =  s + n
      8 return s

UnboundLocalError: local variable 's' referenced before assignment
In [285]:
n = 0
while n < 10: #if this condition is something that never occurs then while loop will go in infinite loop
    print(n)
    n = n + 1
0
1
2
3
4
5
6
7
8
9
In [290]:
inputs = []
for i in range(3):# a convetion to repeate any activity n time
    x = input("Enter " + str(i) +"th input:")
    inputs.append(x)
In [287]:
inputs
Out[287]:
['hello', 'vikrant', 'arcesium']
In [288]:
def take_inputs(n):
    inputs = []
    for i in range(n):# a convetion to repeate any activity n time
        x = input("Enter " + str(i) +"th input:")
        inputs.append(x)
    return inputs
In [289]:
take_inputs(2)
Out[289]:
['hello', 'lksjdsa']
In [ ]: