Module 1 - Day 2

Quick recap

names = ["vikrant", "srinath", "akanksha", "alice"] # use square bracket to create list
names[0]
'vikrant'
names[-1] # last element
'alice'
person = {"name":"Alex", "gender":"Male", "age":57, "city":"Newyork"} # use curley brackets to make dictionary
person
{'name': 'Alex', 'gender': 'Male', 'age': 57, 'city': 'Newyork'}
person['name']
'Alex'
person['city']
'Newyork'

Functions

Built in functions.

  • len : will find length of a list, string, dictionary (for that matter any collection)
len(names) # how many items are there in name
4
names
['vikrant', 'srinath', 'akanksha', 'alice']
len(person) # how many key,value pairs are there in person
4
x = "this is some text ..a literal value"
len(x)
35
len("this is another sentence")
24

Here len is function name , and names, person or x these are called as paramters or arguments of a function

print(x) # it converts the objects or parameters that you pass into text
this is some text ..a literal value
num = 545454
print(num)
545454
print(names)
['vikrant', 'srinath', 'akanksha', 'alice']
names
['vikrant', 'srinath', 'akanksha', 'alice']
x
'this is some text ..a literal value'
print(x)
this is some text ..a literal value
x # this is not print, it is help given by this interpreter to the developer... that what object you are looking at. it is always for last line
'this is some text ..a literal value'
x
person
names # you will see output of only last line
['vikrant', 'srinath', 'akanksha', 'alice']
print(x)
print(person)
print(names)
this is some text ..a literal value
{'name': 'Alex', 'gender': 'Male', 'age': 57, 'city': 'Newyork'}
['vikrant', 'srinath', 'akanksha', 'alice']
print(x, names, person)
this is some text ..a literal value ['vikrant', 'srinath', 'akanksha', 'alice'] {'name': 'Alex', 'gender': 'Male', 'age': 57, 'city': 'Newyork'}
print("hello", "world")
hello world
textnum = "42"
textnum * 2 # it will treat this as a string...
'4242'
int(textnum) # int will convert the text into integer
42
num = int(textnum)
num * 2
84
2**100
1267650600228229401496703205376
str(3434545) # it will convert a number into text (decimal format digits)
'3434545'
str(names)
"['vikrant', 'srinath', 'akanksha', 'alice']"
str(names)
"['vikrant', 'srinath', 'akanksha', 'alice']"
float("34.6")*2
69.2
"34.6"*2
'34.634.6'
nums = [1, 2, 3, 4, 5, 6, 7]
max(nums)
7
min(nums)
1
sum(nums)
28

problem - Find number of digits in 2**100

len(45454545) # this is not easy task for python. internally python stores integers, floats, in binary format!
TypeError: object of type 'int' has no len()
str(45455454)
'45455454'
text = str(343434)
len(text) # number of digits
6
n = 2**100
len(n)
TypeError: object of type 'int' has no len()
n
1267650600228229401496703205376
textn = str(n)
textn
'1267650600228229401496703205376'
len(textn)
31
n = 2**100
textn = str(n)
digits = len(textn)
print("2**100 has", digits, "digits")
2**100 has 31 digits
len(str(2**100)) # nested call of function.. innermost will be executed first
31

List/string slicing

text = "Some random text for learning python"
len(text)
36
text[35]
'n'
text[5:11] # get chars starting from 5th index till 11 (excluding)
'random'
text[0:11]
'Some random'
text[:11] # take first 11 items
'Some random'
text[11:36] # drop first 11
' text for learning python'
text[11:]
' text for learning python'
text[2:25:2] # start at 2nd location, till 25th (exluding) and alternate ..every second char
'm admtx o er'
text[1:30:3]
'o nme reng'

Most generic format for list/text slice is

text[start:end:spacing]

and leave anything as empty , it will be taken as default

  • start default is 0
  • end default is length the list or string
  • spacing default is 1
digits = [0, 1, 2, 3, 4]
range(10)
range(0, 10)
digits = list(range(10))
digits
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
digits[:5] # take first five items
[0, 1, 2, 3, 4]
digits[5:] # drop first five items
[5, 6, 7, 8, 9]
digits[:8:2] # take till 8th items but alternate
[0, 2, 4, 6]
digits[::2]
[0, 2, 4, 6, 8]
digits[1::2]
[1, 3, 5, 7, 9]
digits[::] # what will this be?
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
digits[:] # copy
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
rnums = range(10) # generate integers from 0 till 9
list(rnums) # list ..built in function
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

Creating your own functions

find_digits(2**100)
NameError: name 'find_digits' is not defined
def find_digits(num):
    text = str(num)
    digits = len(text)
    return digits

print("Function was defined")
Function was defined
find_digits(2**100)
31
find_digits(43543543)
8
def say_hello(name):
    print("Hello", name) # this function does not have return
say_hello("Arcesium")
Hello Arcesium
def find_digits_1(num):
    return len(str(num))
X
NameError: name 'X' is not defined
def func(arg):
    X = arg*2
    return X
X
NameError: name 'X' is not defined
func(4)
8
X
NameError: name 'X' is not defined
def abc(a):
    x = a
    print(x)
abc(s) 
NameError: name 's' is not defined
abc("s") # when you call a function while calling, the arguments that you pass should be a variable (which is already defined) or it should be a literal
s

when you call a function while calling, the arguments that you pass should be a variable (which is already defined) or it should be a literal

def compound_interest(P, n, r, t):
    """ Compute compound interest
    P(1+r/n)^nt"""
    term1 = (1 + r/n)
    term2 = n*t
    return P*term1**term2
return 3
SyntaxError: 'return' outside function (1894142552.py, line 1)
def add(a, b):
    return a+b
return a + b # 
SyntaxError: 'return' outside function (1747252886.py, line 1)
def anotherfunc():
    return 34 # after this return statement .. no statements will be executed after this
    return 35

Calling a function Vs Function

Here are some common mistakes that new comers do in python while defining a function

def add(2, 3): # incorrect... there can not be literal in definition
    return 2 +3
SyntaxError: invalid syntax (1316878033.py, line 1)
def add("a" , "b"):
    return a + b
SyntaxError: invalid syntax (501912310.py, line 1)
def add("a" , "b"):
    return "a" + "b"
SyntaxError: invalid syntax (180268243.py, line 1)
def add(a, b): # the argument are like variable names
    return a + b
def add(x, y):
    # inside the function body ... all staetements should make use if varaibles defined as arguments/parameters of a function
    return x+y
add(5, 6)
11
add("a", "b")
"a" + "b"
'ab'
add("a", "b")
'ab'
add("5", "6")
'56'
add("5" , 6)
TypeError: can only concatenate str (not "int") to str
a, b, = 20, 30
add(4,5)
9
a
20
b
30
%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*x
%verify_problem square
✓ verify square(2)
✓ verify square(4)
🎉 Congratulations! You have successfully solved problem square!!