Module 1 - Day 4

Login to Lab using your credentials. There is a notebook with name 1-4.ipynb already created for you. Open that and use it for today’s training.

Shut down all previous notebooks.

Quick recap

  • String metthods - isupper, isalpha, isnumeric, upper, lower, split, join, replace, startswith, endswith
  • list methods - append, remove, insert, extend
"hello world this is just a sentence".split() # it splits in white spaces
['hello', 'world', 'this', 'is', 'just', 'a', 'sentence']
"a-b-c-d-e".split("-")
['a', 'b', 'c', 'd', 'e']
",".join(['a', 'b', 'c', 'd', 'e'])
'a,b,c,d,e'
print("\n".join(['a', 'b', 'c', 'd', 'e']))
a
b
c
d
e
empty = []
empty.append(0) # also note that few methods do their job but do not return
empty
[0]
empty.insert(0, 2)
empty
[2, 0]

Look back at local and global context

Problem

  x = [1, 1, 1]

  def appendzero(y):
      y.append(0)      # mehtods operate on the data of the object

  appendzero(x)
  print(x)
x = [1, 1, 1]

def appendzero(y):
    y.append(0)      # mehtods operate on the data of the object

appendzero(x)
print(x)
[1, 1, 1, 0]

Problem

  x = [1, 1, 1]

  def appendzero(y): # y is already given as an argument
      y = y + [0]

  appendzero(x)
  print(x)
[1, 1, 1] + [2] # this creates a new list
[1, 1, 1, 2]
ones = [1, 1, 1, 1]
twos = [2, 2]
ones + twos
[1, 1, 1, 1, 2, 2]
ones
[1, 1, 1, 1]
twos
[2, 2]
x = [1, 1, 1]

def appendzero(y): # y is already given as an argument
    y = y + [0] # beacasue of assignment operator, y is local so we willl not see any change in x

appendzero(x)
print(x)
[1, 1, 1]

x = [1, 1, 1]

def appendzero(y):
    y.append(0)      # mehtods operate on the data of the object

appendzero(x) # this will link y to same place as x. if I call method og y , it will actually call of x
print(x)
[1, 1, 1, 0]
x = [1, 1, 1]

def appendzero(y): # y is already given as an argument
    y = y + [0] # beacasue of assignment operator, y is local so we willl not see any change in x
    return y

z = appendzero(x) # z = x + [0]
z
[1, 1, 1, 0]
x = appendzero(x) # this will result in new value x
x
[1, 1, 1, 0]
x = [1, 1, 1]
appendzero(x) # this will show the result of appendzero (return value)
[1, 1, 1, 0]
x
[1, 1, 1]
1  + 2
2 + 4234
543 + 435
2**100 # onlt this line's output will be visible
1267650600228229401496703205376

Function arguments

def cylinder_volume(radius, height): # radius , height are calles as argument
    return 3.14*radius*radius *height
cylinder_volume(1, 10) # I paased radius first and then height... Positional argumnts
31.400000000000002
cylinder_volume(10, 1) # this will result into different values... It si allowed to alter the position of argument
314.0
cylinder_volume(height=10, radius=1) # this is called named arguments!
31.400000000000002
def take_inputs():
    radius = input("Enter the radius in cm")
    height = input("Enter the height in cm")
    return radius, height
    
def interactive_cyl_volume():
    r, h = take_inputs()
    return cylinder_volume(radius=r, height=h)
interactive_cyl_volume()
Enter the radius in cm 1
Enter the height in cm 5
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
Cell In[44], line 1
----> 1 interactive_cyl_volume()

Cell In[43], line 8, in interactive_cyl_volume()
      6 def interactive_cyl_volume():
      7     r, h = take_inputs()
----> 8     return cylinder_volume(radius=r, height=h)

Cell In[36], line 2, in cylinder_volume(radius, height)
      1 def cylinder_volume(radius, height): # radius , height are calles as argument
----> 2     return 3.14*radius*radius *height

TypeError: can't multiply sequence by non-int of type 'float'
def cylinder_volume(radius, height): # radius , height are calles as argument
    return 3.14*radius*radius *height

def take_inputs():
    radius = input("Enter the radius in cm")
    height = input("Enter the height in cm")
    return float(radius), float(height) # sequence is important
    
def interactive_cyl_volume():
    r, h = take_inputs()
    return cylinder_volume(radius=r, height=h) 
interactive_cyl_volume()
Enter the radius in cm 1
Enter the height in cm 5
15.700000000000001
cylinder_volume(1, 10)
31.400000000000002
cylinder_volume(1, height=5)
15.700000000000001
def func(a, b, c):
    return a - b + c
func(2, 1, 3)
4
func(c=3, a=2, b=1) # the positions have changed but I gave the names
4
func(2, c=3, b=1)
4
func(2, b=1, c=3)
4
func(b=1 , c=3, 2)
  Cell In[58], line 1
    func(b=1 , c=3, 2)
                     ^
SyntaxError: positional argument follows keyword argument
func(b=1, c=3)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
Cell In[59], line 1
----> 1 func(b=1, c=3)

TypeError: func() missing 1 required positional argument: 'a'
def fun(a=0, b=0, c=0): #default values
    return a - b + c
fun() # everything taken as 0
0
fun(2, 3, 4)
3
fun(2, c=4)
6
fun(1, 2)
-1
fun(2, c=5)
7
fun(2, , 4)
  Cell In[67], line 1
    fun(2, , 4)
           ^
SyntaxError: invalid syntax

conditions

s = "this statement start with this"
s.startswith("this")
True
"this" in s
True
students = ["Alex", "Alice", "Barkha", "Tom", "Jerry"]
"mahesh" in students
False
"Alice" in students
True
"mahesh" not in students
True
"this" in s
True
"that" in s
False
"that" not in s
True
a, b = 2, 3
a == b # if a is equal to b
False
a != b # a is not equal to b
True
a > b
False
a >= b
False
a <= b
True
a >= 0
True
a >=0 and b >=0 # true only if both are true
True
a>=0 or b >=0 # true if any one is true
True
"this" in s and "that" not in s
True
if a > b: # code block
    print("a > b")
    print("one more line")
elif "that" in s:
    print("that in s")
else:
    print("none of the conditions matched")
none of the conditions matched
def max2(x, y):
    if x>y:
        return x
    else:
        return y
    
max2(5, 7)
7

problem

Write a function maximum3 which finds miximum from three numbers

max([1, 2, 3, 4, 5, 6, 7, 8])
8
l = [1, 2, 3, 4]
max(l)
4
def maximum3(x, y, z):
    if x > y and x > z:
        return x
    elif y > x and y > z:
        return y
    else:
        return z
maximum3(2, 4, 5)
5
maximum3(2, 5, 3)
5
maximum3(10,2, 3)
10
def maximum3_(x, y, z): # this will less probability of bugs
    m1 = max2(x, y)
    return max2(m1,z) 
text = input("give comma separated numbers")
give comma separated numbers 1,2,3
text
'1,2,3'
text.split(",")
['1', '2', '3']

loops

textnums = text.split(",")
textnums
['1', '2', '3']
for i in textnums:
    print(i, type(i))
    
1 <class 'str'>
2 <class 'str'>
3 <class 'str'>
print("hello")
hello
print('1')
1
print(1)
1
empty = []
for i in textnums:
    empty.append(int(i))
    
    
empty
[1, 2, 3]
def take_numbers_input():
    text = input("Give integers sapareated by comma")
    strnums = text.split(",")
    nums = []
    for s in strnums:
        n = int(s)
        nums.append(n)

    return nums
integers = take_numbers_input()
Give integers sapareated by comma 1,2,3,4,5,6,7,8,11
integers
[1, 2, 3, 4, 5, 6, 7, 8, 11]
for c in "sdhskjdhask":
    print(c)
s
d
h
s
k
j
d
h
a
s
k
for i in [1, 2, 3, 4, 5]:
    print(i)
1
2
3
4
5
for word in s.split():
    print(word)
this
statement
start
with
this
scores = {"Alex":20, "Alice":24, "Tom":23, "Jerry": 25}
for name in scores: # it will go over all the keys from dictionary
    # name is a loop variable which changes value in every iteartion
    print(name, scores[name])
Alex 20
Alice 24
Tom 23
Jerry 25

problem

Write a function product which finds product of all elements from a list. You well be given a list of numbers!

    >>> product([3, 2, 4])
    24
sum(range(10))
45
t = list(range(10))
t
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
product([1, 2, 3, 5])
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
Cell In[131], line 1
----> 1 product([1, 2, 3, 5])

NameError: name 'product' is not defined
return 10
  Cell In[132], line 1
    return 10
    ^
SyntaxError: 'return' outside function
def foo():
    return 10

Let us find product of all these numbers manually

1, 2, 3, 4, 5, 6

1*1 = 1
1*2 = 2
2*3 = 6
6*4 = 24
24*5 = 120
120*6 = 720
def product(nums):
    p = 1
    
    for n in nums:
        p = p * n

    return p
def mysum(nums):
    s = 0
    
    for n in nums:
        s = s + n

    return s
    
product(range(1, 7))
720
list(range(1, 10))
[1, 2, 3, 4, 5, 6, 7, 8, 9]
mysum(range(11))
55
product([1, 2, 3, 4])
24
nums = [1, 2, 34,  6]
product(nums)
408
product(1, 2, 34, 6) # every number here is taken as separate argument
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
Cell In[148], line 1
----> 1 product(1, 2, 34, 6) # every number here is taken as separate argument

TypeError: product() takes 1 positional argument but 4 were given
words
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
Cell In[149], line 1
----> 1 words

NameError: name 'words' is not defined
words = s.split()
words
['this', 'statement', 'start', 'with', 'this']
def findlens(words):
    lens = []
    for w in words:
        l = len(w)
        lens.append(l)
    return lens
findlens(words)
[4, 9, 5, 4, 4]
words
['this', 'statement', 'start', 'with', 'this']
def findsquares(nums):
    
nums
[1, 2, 34, 6]
def f(nums):

    for i in nums:
        s = i*i
        return s # the moment return statement is executed , function is over ..for loop is not complete
f([1, 232,3, 34])
1
def f(nums):

    for i in nums:
        s = i*i # it is single number
    return s
f([1, 2, 34, 5]) # will 
25
def f(nums):
    sqrs = []
    for i in nums:
        s = i*i # it is single number
        sqrs.append(s)
    return sqrs
f(nums)
[1, 4, 1156, 36]