Module 1 - Day 2

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

# Header -> top level header
## Header1 -> second level header
### Header2 -> third level header

Quick recap

  • int
  • float
  • operator-precedence
  • text/string (can not be edited once created)
  • list - ordered collection of object
  • dictinary - it is collection of named values … key:value
  • tuple - similar to list but can not be edited once created
  • variable/literal
  • boolean - True/False
  • None

Functions

\(f(x) = x^{2} + 2x + 1\)

numbers = [1, 2, 3, 4, 5, 6, 7, 8]
sentence = "How are you doing today?"
person = {"name": "Vikrant",
          "address": "Maharashtra",
          "company": "Pipal Academy"}
len(numbers) # this will take any collection as argument
8
len(sentence) # it includes every char in the sentence including spaces, new lines , questioon marks etc.
24
len(person) # it will how many pairs?
3
multiline = """This is first line
this second
and this is third one!"""
multiline
'This is first line\nthis second\nand this is thrid one!'
len(multiline)
53
"\n" # new line
'\n'
"\t" # tab
'\t'
"\\" # windows sep
'\\'
len('\\') # this is one char
1
len("\n")
1
len("\\n")
2
print("there is a \t tab")
there is a   tab
print("one\ntwo")
one
two
print(multiline)
This is first line
this second
and this is third one!
multiline
'This is first line\nthis second\nand this is third one!'
2 + 3
5
print(2+3) # print(5)
5
sum(numbers) # the collection that we are passing as an argument to sum should have numeric values in it
36
words = ["one", "two", "three"]
sum(words)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
Cell In[32], line 1
----> 1 sum(words)

TypeError: unsupported operand type(s) for +: 'int' and 'str'
x,y = 5,10
sum(x, y)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
Cell In[34], line 1
----> 1 sum(x, y)

TypeError: 'int' object is not iterable
sum([x, y])
15
type(x) # this will tel what is the data type stored in this variable
int
type(numbers)
list
type(person)
dict
type(sentence)
str
type(x)
int
x
5
type(10) # literal
int
strten = "10"
strten
'10'
strten + 1
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
Cell In[48], line 1
----> 1 strten + 1

TypeError: can only concatenate str (not "int") to str
int(strten) + 1
11
strten
'10'
strten
'10'
1 + strten
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
Cell In[54], line 1
----> 1 1 + strten

TypeError: unsupported operand type(s) for +: 'int' and 'str'
 min(numbers)
1
max(numbers)
8
sum(person)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
Cell In[57], line 1
----> 1 sum(person)

TypeError: unsupported operand type(s) for +: 'int' and 'str'
sorted([2, 3, 4, 56, 2, 1, 2, 34])
[1, 2, 2, 2, 3, 4, 34, 56]
unordered_nums = [2, 3, 4, 56, 2, 1, 2, 34]
sorted(unordered_nums) # will return new sorted list
[1, 2, 2, 2, 3, 4, 34, 56]
unordered_nums
[2, 3, 4, 56, 2, 1, 2, 34]
len(numbers)
8
sorted(unordered_nums, reverse=True)
[56, 34, 4, 3, 2, 2, 2, 1]
sorted(unordered_nums, reverse=True) # it is a named argument
[56, 34, 4, 3, 2, 2, 2, 1]

Problem

Use python to find total income if the person has five income sources giving income of 123330, 250000, 45555, 232130, 11123

incomes = [123330, 250000, 45555, 232130, 11123]
sum(incomes)
662138
incomes = [123330, 250000, 45555, 232130, 11123]
total_income = sum(incomes)
print("Total income is:", total_income)
Total income is: 662138

Problem

Find number of digits in \(2^{100}\)

type(1.2)
float
float("34.5")
34.5
type("test")
str
str(35)
'35'
2**100
1267650600228229401496703205376
1200 # this is a number/intger in decimal system that we see... but for a computer it just a number
str(12) # python understands that this number 12 should be converted in to char - digits of decimal format
'12'
value = 2**100 
textvalue = str(value)
textvalue
'1267650600228229401496703205376'
len(textvalue)
31

How to write your own function

countdigits(number)

def countdigits(number): # line should end with colon
    textnumber = str(number)
    count = len(textnumber)
    return count
countdigits(2300)
4
def countdigits_(number): # line should end with colon
    textnumber = str(number)
    count = len(textnumber)
    print(count)
countdigits_(2300)
4
digits = countdigits(2300) # this will store result returned by countdigits into variable digits
4
4
x = 4 # this does not show any interpreter response!
digits
4
digits_ = countdigits_(2300)
4
digits_
print(digits_)
None
countdigits_(2**100)
31
c = countdigits_(2**100)
31
print(c)
None
def say_hello(name):
    print("Hello", name)
say_hello("Arcesium")
Hello Arcesium
def add(a, b):
    return a+b
6546354 + 423423 * add(343, 3434)
1605815025
454 * countdigits(2**100)
14074
454 * countdigits_(2**100)
31
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
Cell In[103], line 1
----> 1 454 * countdigits_(2**100)

TypeError: unsupported operand type(s) for *: 'int' and 'NoneType'

Example

def twice(x):
    return 2*x

def double(x):
    print(2*x)
twice(twice(10)) # nested calling of a function
40
twice(10)
20
twice(20)
40
twice(twice(10)) # in this inner most function call will be executed first
40
del twice # just like variable you can delete
twice(2)
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
Cell In[120], line 1
----> 1 twice(2)

NameError: name 'twice' is not defined
def twice(x):
    return 2*x

def double(x):
    print(2*x)
twice(twice(twice(20)))
160
double(20)
40
double(double(20))
40
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
Cell In[125], line 1
----> 1 double(double(20))

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

TypeError: unsupported operand type(s) for *: 'int' and 'NoneType'
def add3(a, b, c): # as many arguments you define here, your function should be called with those many arguments
    return a + b + c
add3(2, 3, 4)
9
add3(2, 3)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
Cell In[128], line 1
----> 1 add3(2, 3)

TypeError: add3() missing 1 required positional argument: 'c'
add3(2, 3, 4, 5)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
Cell In[129], line 1
----> 1 add3(2, 3, 4, 5)

TypeError: add3() takes 3 positional arguments but 4 were given

Functions and local variables

def add(x, y): # this x and y is not related to x and y defined above , global space
    return x + y
x
4
y
10
add(10, 20) # after this call is over x and y defined inside function are lost
30
x
4
y
def function(numbers): # when you write the logic of the function assumes the type of argument
    return sum(numbers)
scores = [20, 19, 18, 20, 18]
function(scores)
95
def function2(numbers): # when you write the logic of the function assumes the type of argument
    return sum(numbers), max(numbers)
function2(scores)
(95, 20)
total, max_ = function2(scores)
max = 10 # I lost the connection to original variable where it was pointing
max(scores)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
Cell In[149], line 1
----> 1 max(scores)

TypeError: 'int' object is not callable
del max
max(scores)
20
total, max_ = function2(scores)
total
95
max_
20

List of built in functions

  • int
  • float
  • str
  • sum
  • min
  • max
  • sorted
  • print
  • len
  • list
list("Python")
['P', 'y', 't', 'h', 'o', 'n']
%load_problem square
Problem: Square

Write a function square to compute the square of a number.

>>> square(4)
16

You can verify your solution using:

%verify_problem square

# your code here
def square(x):
    return x

square(5)
5
%verify_problem square
Found 2 checks
✗ verify square(2)
  expected: 4
  found: 2
✗ verify square(4)
  expected: 16
  found: 4
💥 Oops! Your solution to problem square is incorrect or incomplete.