7  Module 1 - Day 2

Today’s topics

Make use of notebook module1-day2.ipynb , already created in your jupyter environment.

7.1 More built in function

numbers = [1, 2, 3, 4]
mixed = [1, "word", [1, 1, 1]]
stock = {"name":"APPLE",
        "value": 256,
        "volume": 200}
stock['name']
'APPLE'
number[0]
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
Cell In[5], line 1
----> 1 number[0]

NameError: name 'number' is not defined
len(mixed)
3
len("test data as text")
17
len(stock) # number pairs
3
str(1223123)
'1223123'
str(mixed)
"[1, 'word', [1, 1, 1]]"
sum(numbers)
10
min(numbers)
1
max(numbers)
4
sorted(numbers)
[1, 2, 3, 4]
words = ["one", "two", "three", "four", "five", "six"]
sorted(words)
['five', 'four', 'one', 'six', 'three', 'two']
max(words)
'two'
min(words)
'five'
print(words)
['one', 'two', 'three', 'four', 'five', 'six']
text = "Hello Python"
text
'Hello Python'
print(text)
Hello Python
text[0]
'H'
print(text[0])
H
print("Hello World!")
Hello World!
name = input("Enter your name")
Enter your name vikrant
name
'vikrant'
x = input("Enetr an integer")
Enetr an integer 45
x
'45'
y = int(x)
y
45
int("test")
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
Cell In[35], line 1
----> 1 int("test")

ValueError: invalid literal for int() with base 10: 'test'
int("45.5")
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
Cell In[36], line 1
----> 1 int("45.5")

ValueError: invalid literal for int() with base 10: '45.5'
int(45.5)
45
int("45")
45
float("45.5")
45.5
r = 25.5
r
25.5
int(r)
25

7.2 list/text slicing

text = "Lets take this as an example"
text[0]
'L'
text[2:10] # start at index 2 and go till  index 10 (exluding 10.. means go till 9)
'ts take '
text[1:20:2]
'estk hsa n'
primes = [1, 2, 3, 5, 7, 11, 13, 17, 19, 23]
primes[1:6:2]    # start, end, interval
[2, 5, 11]
primes[:5] # take first five
[1, 2, 3, 5, 7]
primes[3:] # drop first three items
[5, 7, 11, 13, 17, 19, 23]
primes[:] # copy
[1, 2, 3, 5, 7, 11, 13, 17, 19, 23]
primes
[1, 2, 3, 5, 7, 11, 13, 17, 19, 23]
x = primes # this is not copy.. this is just an alias to same object
x
[1, 2, 3, 5, 7, 11, 13, 17, 19, 23]
x[0] = 0
primes
[0, 2, 3, 5, 7, 11, 13, 17, 19, 23]
y = primes[:] # this is real copy
primes
[0, 2, 3, 5, 7, 11, 13, 17, 19, 23]
y
[0, 2, 3, 5, 7, 11, 13, 17, 19, 23]
y[0] = 1
y
[1, 2, 3, 5, 7, 11, 13, 17, 19, 23]
primes
[0, 2, 3, 5, 7, 11, 13, 17, 19, 23]
primes[:2]  # take first two
[0, 2]
primes[:3]  # take first three
[0, 2, 3]
primes[:4] # this is a comment and I can write even junk here! 
[0, 2, 3, 5]

7.2.1 When do we use parenthesis?

  • We use parenthesis when we want to create tuple

  • we use parenthesis to call a function (we have seen only builtins) and between parenthesis we give input to the function

    print("hello")
    int("24")
    sum(primes)
x
[0, 2, 3, 5, 7, 11, 13, 17, 19, 23]
x()
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
Cell In[67], line 1
----> 1 x()

TypeError: 'list' object is not callable
name() # it will teat the variable name as function 
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
Cell In[68], line 1
----> 1 name() # it will teat the variable name as function 

TypeError: 'str' object is not callable
name
'vikrant'
text(1) # it is treating text as a function and 1 as input to that function
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
Cell In[70], line 1
----> 1 text(1) # it is treating text as a function and 1 as input to that function

TypeError: 'str' object is not callable
int(5) # the input is already integer
5
int("5") # the input is text, here the function will do work on the chars and convert in into integer and then that will be ouput
5
int("5.5")
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
Cell In[74], line 1
----> 1 int("5.5")

ValueError: invalid literal for int() with base 10: '5.5'
int(5.5)
5
x = input("Eneter an integer")
Eneter an integer 25.5
x
'25.5'
int(x)
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
Cell In[78], line 1
----> 1 int(x)

ValueError: invalid literal for int() with base 10: '25.5'
int("25.5")
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
Cell In[79], line 1
----> 1 int("25.5")

ValueError: invalid literal for int() with base 10: '25.5'
type(x)
str
type(primes)
list
type(5)
int
type(45.5)
float
text
'Lets take this as an example'
text[::-1] # reverse the text/list
'elpmaxe na sa siht ekat steL'

7.3 Creating custom functions

def square(x):
    s = x * x
    return s
square(42)
1764

7.3.1 Calling Vs Functioon defination

def add(2, 3): # incorrect! you can not have literals here!
    return 2 + 3

def add("a", "b"): #incorrect!
    return "a" + "b"

def add("a", "b"): #incorrect!
    return a + b 

def add(a, b): # correct way
    return a + b
  Cell In[6], line 1
    def add(2, 3): # incorrect! you can not have literals here!
            ^
SyntaxError: invalid syntax
1 # this is literal
1
x = 1
x # this is variable
1
y = "454" + 5
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
Cell In[7], line 1
----> 1 y = "454" + 5

TypeError: can only concatenate str (not "int") to str
y
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
Cell In[8], line 1
----> 1 y

NameError: name 'y' is not defined
a # is a variable
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
Cell In[9], line 1
----> 1 a # is a variable

NameError: name 'a' is not defined
"a" # is a text... it is a literal value
'a'

problem Compound interest is calculated using formula P (1 + r/n)^nt For this formula, P is the principal amount, r is the rate of interest per annum, n denotes the number of times in a year the interest gets compounded, and t denotes the number of years. Use python to compute compound interest for principle amount of 26780, rate of interest 7%, interest is compounded 4 quarterly, and amount is invested for 5 years.

write a function compounded_amount which will take P, r, n, t as inputs and will return the computed value as per above formula

def square(a):
    """computes square of a number, make note that a is a number
    """
    return a*a

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

def compounded_amount(P, r, n, t):
    """Please make note that r should be given as fraction of 100
    """
    pass #empty statement
help(square)
Help on function square in module __main__:

square(a)
    computes square of a number, make note that a is a number
help(compounded_amount)
Help on function compounded_amount in module __main__:

compounded_amount(P, r, n, t)
    Please make note that r should be given as fraction of 100
a,b = 1, 3
ab
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
Cell In[15], line 1
----> 1 ab

NameError: name 'ab' is not defined
a*b
3
a (1 +b)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
Cell In[17], line 1
----> 1 a (1 +b)

TypeError: 'int' object is not callable
a*(1+b)
4
def compounded_amount(P, r, n, t):
    """Please make note that r should be given as fraction of 100
    """
    return P*(1 + r/n) ** (n*t)
compounded_amount(26000, 0.07, 4, 5)
36784.2330896508
def compounded_amount(P, r, n, t):
    r = r/100
    return P*(1 + r/n) ** (n*t)
compounded_amount(26000, 7, 4, 5)
36784.2330896508
compounded_amount(250000, 7, 4, 5)
353694.54893895
compounded_amount(250000, 6, 3, 10)
452840.3960258387
def hello(name):
    print("Hello", name)
hello("python")
Hello python
hello("vikrant")
Hello vikrant
def compounded_amount(P, r, n, t):
    r = r/100
   return P*(1 + r/n) ** (n*t) # this has different indentation that above line
   # in one code block all the lines should have same indentation
  File <string>:3
    return P*(1 + r/n) ** (n*t) # this has different indentation that above line
                                                                                ^
IndentationError: unindent does not match any outer indentation level
def compounded_amount(P, r, n, t):
    r = r/100
    return P*(1 + r/n) ** (n*t)
x = 10
def foo(y):
    print(x, y) # you can access global variable for reading
foo(5)
10 5
del x
x
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
Cell In[34], line 1
----> 1 x

NameError: name 'x' is not defined
x = 10
def addone():
    x = x + 1 # the assignement operator will create a new name in local name space!
addone()
---------------------------------------------------------------------------
UnboundLocalError                         Traceback (most recent call last)
Cell In[37], line 1
----> 1 addone()

Cell In[36], line 3, in addone()
      2 def addone():
----> 3     x = x + 1

UnboundLocalError: cannot access local variable 'x' where it is not associated with a value
x = 20 # global namespace
y = 30

def foo():
    x = 10 # these local variable inside function
    y = 5
    print(x,y)
foo()
10 5
print(x, y)
20 30
def bar():
    print(x, y) # when x and y are defined in local name space 
    # it will refer to global namesapce
bar()
20 30

def funclocal():
    X_ = 45
    Y_ = 42
    print(X_, Y_)

funclocal() # this statement is outside function...look at indentation
print(X_, Y_) # there is no variable X_ in global name space
45 42
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
Cell In[46], line 7
      4     print(X_, Y_)
      6 funclocal() # this statement is outside function...look at indentation
----> 7 print(X_, Y_)

NameError: name 'X_' is not defined
blah = blah + 1
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
Cell In[47], line 1
----> 1 blah = blah + 1

NameError: name 'blah' is not defined

7.4 Functions with return value

A function that does not have return statement.. returns None by default

def double(x):
    print(2*x)
double(5)
10
x = double(5)
10
print(x)
None
def cube(a):
    return a**3

def twice(x):
    return 2*x


twice(cube(3))  # nested function call
# first cube will be called
# twice(27)
# 54
54
twice(twice(5))
20
double(double(5))
# 10 will be printed
# double(None)
# 2*None
10
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
Cell In[54], line 1
----> 1 double(double(5))
      2 # 10 will be printed
      3 # double(None)
      4 # 2*None

Cell In[48], line 2, in double(x)
      1 def double(x):
----> 2     print(2*x)

TypeError: unsupported operand type(s) for *: 'int' and 'NoneType'
2*None
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
Cell In[55], line 1
----> 1 2*None

TypeError: unsupported operand type(s) for *: 'int' and 'NoneType'
hello("Python")
Hello Python
%load_problem sqaure
---------------------------------------------------------------------------
FileNotFoundError                         Traceback (most recent call last)
Cell In[57], line 1
----> 1 get_ipython().run_line_magic('load_problem', 'sqaure')

File /opt/tljh/user/lib/python3.12/site-packages/IPython/core/interactiveshell.py:2511, in InteractiveShell.run_line_magic(self, magic_name, line, _stack_depth)
   2509     kwargs['local_ns'] = self.get_local_scope(stack_depth)
   2510 with self.builtin_trap:
-> 2511     result = fn(*args, **kwargs)
   2513 # The code below prevents the output from being displayed
   2514 # when using magics with decorator @output_can_be_silenced
   2515 # when the last Python token in the expression is a ';'.
   2516 if getattr(fn, magic.MAGIC_OUTPUT_CAN_BE_SILENCED, False):

File ~/training/pipalhub-magic/pipalhub_magic.py:361, in PipalMagics.load_problem(self, arg)
    357 problem_text = f"**Problem: {arg}**"
    358 # contents = "# %load_problem " + arg
    359 # self.shell.set_next_input(contents, replace=True)
--> 361 problem = Problem.find(arg)
    362 display(problem)
    364 if problem.problem_type == "script":

File ~/training/pipalhub-magic/pipalhub_magic.py:78, in Problem.find(cls, name)
     75 @classmethod
     76 def find(cls, name):
     77     path = Path(PROBLEM_ROOT) / name / "problem.yml"
---> 78     metadata = yaml.safe_load(path.open())
     79     return cls(name, metadata)

File /opt/tljh/user/lib/python3.12/pathlib.py:1013, in Path.open(self, mode, buffering, encoding, errors, newline)
   1011 if "b" not in mode:
   1012     encoding = io.text_encoding(encoding)
-> 1013 return io.open(self, mode, buffering, encoding, errors, newline)

FileNotFoundError: [Errno 2] No such file or directory: '/opt/training/problems/sqaure/problem.yml'
def twice(x):
    return 2*x  # this will return 2*x

def double(x):
    print(2*x) # this will print 2*x and return None
twice(twice(5))
twice(10)
20 as returedn value
double(double(5))
double(None)   # will also print 10
2*None
double(double(5))
10
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
Cell In[60], line 1
----> 1 double(double(5))

Cell In[59], line 5, in double(x)
      4 def double(x):
----> 5     print(2*x)

TypeError: unsupported operand type(s) for *: 'int' and 'NoneType'
x = min([1, 2, 3, 4, 5])
x
1
y = print("hello")
hello
print(y)
None
def foo():
    pass
z = foo()
print(z)
None
def add(a, b):
    a + b
z = add(5, 6)
print(z)
None
def add(a, b):
    return a + b
z = add(5, 6)
z
11

7.5 Methods

text = "This is a statement for testing methods!" 
text[0] = "t"
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
Cell In[79], line 1
----> 1 text[0] = "t"

TypeError: 'str' object does not support item assignment
text.upper()
'THIS IS A STATEMENT FOR TESTING METHODS!'
text
'This is a statement for testing methods!'
text.upper()
'THIS IS A STATEMENT FOR TESTING METHODS!'
name = "python"
text
'This is a statement for testing methods!'
name
'python'
name.upper()
'PYTHON'
name.endswith("ON")
False
name
'python'
name.endswith("on")
True
text
'This is a statement for testing methods!'
text.startswith("This")
True
text
'This is a statement for testing methods!'
text.replace(" ", "_")
'This_is_a_statement_for_testing_methods!'
text.replace("!", "?")
'This is a statement for testing methods?'
print("hello", "there",sep="\n")
hello
there