def twice(x):
return 2*x
def say_hello(name):
print("Hello", name,"!")Module 1 - Day 3
twice(4) # it looks like print but it is not .. it is response of interpreter to call of function8
say_hello("arcesium")Hello arcesium !
def func():
pass # pass is a statement that does nothingdef func1():
SyntaxError: incomplete input (2040221739.py, line 5)
func() # there will not print, no interpreter responsex_2 = twice(5)x_210
result = func()result # there is nothing in itprint(result)None
Any function that does not have return statement in it, will by defualt resturn None
def say_hello(name):
print("Hello", name,"!")r_hello = say_hello("arcesium") Hello arcesium !
print(r_hello) # because there is not return statement in say_helloNone
Two types of functions
- one that does some computation and returns the value
- one that does something (print to screen, write to file, starting service on the system) ..may not return value
%load_problem simple_interestWrite a function simple_interest to compute simple interest. It takes three arguments, principal amount, rate of interest and time (in years) and returns simple interest accumulated on given principal amount for given number of years for given rate of interest.
>>> simple_interest(10000,8,5)
4000.0
>>> simple_interest(100,3,1)
3.0
You can verify your solution using:
%verify_problem simple_interest
# your code here
def simple_interest(P, N, R):
return P*N*R/100
%verify_problem simple_interest✓ simple_interest(100, 4, 5)
✓ simple_interest(100, 5, 5.0)
🎉 Congratulations! You have successfully solved problem simple_interest!!
%load_problem meanWrite a function mean to compute the arthematic mean of a list of numbers.
The arthemetic mean of N numbers is computed by adding all the N numbers and dividing the total by N.
The function takes the list of numbers as argument and returns the mean.
>>> mean([1, 2, 3, 4, 5])
3.0
You can verify your solution using:
%verify_problem mean
# your code here
nums = list(range(21))len(nums)21
sum(nums)210
max(nums)20
min(nums)0
sum = 1 + 2 + 3 + 4sum10
nums[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]
sum(nums)TypeError: 'int' object is not callable
sum10
sum10
del sum # this deletes the variable from namespacesum_ = 1 + 2 + 3 + 4sum_10
sum(nums)210
nums[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]
sum(nums)210
def mean(numbers):
sum_ = sum(numbers)
return sum_/len(numbers)%verify_problem mean✓ mean([1, 2, 3, 4, 5])
✓ mean([5])
🎉 Congratulations! You have successfully solved problem mean!!
x = [10, 20, 30, 40, 50]sum(x)150
x[0] + x[1] + x[2] + x[3] + x[4]150
def mean_first_n(n):
nums = range(n)
return sum(nums)/len(nums)ones = [1, 1, 1, 1, 1]len(ones) # becasue there are five ones in it..length will be 55
str(ones)'[1, 1, 1, 1, 1]'
text = str(ones)text[0]'['
text[1]'1'
text[2]','
text[3]' '
mean([1, 1, 2, 3, 4])2.2
mean(1, 2) # this means I am passing two arguments 1 and 2TypeError: mean() takes 1 positional argument but 2 were given
mean([1, 2]) # this means I am passing one argument as a list1.5
def twice(x):
return 2*x
def twice1(x):
print(2*x)twice(5)10
twice1(5)10
x = twice(5)x10
y = twice1(5)10
print(y)None
twice(twice(5))20
twice1(twice1(5)) # the inner most call will be successful, 10
TypeError: unsupported operand type(s) for *: 'int' and 'NoneType'
None*2TypeError: unsupported operand type(s) for *: 'NoneType' and 'int'
String Methods
len, sum, int, str, list, range ..these are some built in functions that we saw. Many more functionalies are provided by methods which come as part of string object
sentence = "There Are Few Wise Words"sentence.startswith("The") # this expects one argumentTrue
sentence.endswith("x")False
sentence.endswith("s")True
sentence.endswith("Words")True
sentence.isupper() # just asking a questionFalse
True # boolean data typesTrue
FalseFalse
sentence.upper() # this will return a new text with everything converted upper case'THERE ARE FEW WISE WORDS'
sentence'There Are Few Wise Words'
sentence.isalpha() # does this have all chars from english alphabetsFalse
"asasas".isalpha()True
"test123".isalnum() # does this have alphabets or numbers?True
text = "hello world"text.capitalize()'Hello world'
text.title()'Hello World'
sentence'There Are Few Wise Words'
sentence.replace("Wise", "Foolish")'There Are Few Foolish Words'
help(sentence.replace)Help on built-in function replace:
replace(old, new, count=-1, /) method of builtins.str instance
Return a copy with all occurrences of substring old replaced by new.
count
Maximum number of occurrences to replace.
-1 (the default value) means replace all occurrences.
If the optional argument count is given, only the first count occurrences are
replaced.
sentence.split() # this will split given text into words... word boundaries are whitespaces['There', 'Are', 'Few', 'Wise', 'Words']
words = sentence.split()words['There', 'Are', 'Few', 'Wise', 'Words']
words[0]'There'
words[-1]'Words'
len(sentence.split()) # how many words are there 5
dashed = "This-is-another-text-with-dash-in-it-instead-of-space"dashed.split() # beacasue by default word boundary is taken as while spaces['This-is-another-text-with-dash-in-it-instead-of-space']
dashed.split("-")['This',
'is',
'another',
'text',
'with',
'dash',
'in',
'it',
'instead',
'of',
'space']
"this,is,comma,separated".split(",")['this', 'is', 'comma', 'separated']
multilinetext = """this is first line
this is second line
this is third line"""print(multilinetext)this is first line
this is second line
this is third line
multilinetext # interprester response ... here you will be able to see the exact character stored in this text'this is first line\nthis is second line\nthis is third line'
print(multilinetext)this is first line
this is second line
this is third line
filetext = '''some lines
from a file
are here
and we have read them
using python'''filetext'some lines\nfrom a file\nare here\nand we have read them\nusing python'
filetext.split("\n") # this will split the text using newline char ... so I will get list of lines['some lines',
'from a file',
'are here',
'and we have read them',
'using python']
lines = filetext.split("\n")lines['some lines',
'from a file',
'are here',
'and we have read them',
'using python']
nums[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]
a = [1, 2, 3, 4, 5]a = [1,
2,
3,
4,
5]a[1, 2, 3, 4, 5]
dashed.replace("-", " ") # this will return new string with the changes. original remains as it is'This is another text with dash in it instead of space'
dashed'This-is-another-text-with-dash-in-it-instead-of-space'
Any string method will not change the original string, it will always return a new string
string is immutable object, once created it can not be modified.
sometext = " -hello-one-two-three"sometext.split("-")[' ', 'hello', 'one', 'two', 'three']
sometext.strip() # string will remove trailing spaces'-hello-one-two-three'
sometext.strip().split("-")['', 'hello', 'one', 'two', 'three']
dashed'This-is-another-text-with-dash-in-it-instead-of-space'
dashed.replace("-"," ").replace("text", "string") # this is mehtod chaining'This is another string with dash in it instead of space'
len(str(12131)) # this is nested call of functions5
dashed.split("-")['This',
'is',
'another',
'text',
'with',
'dash',
'in',
'it',
'instead',
'of',
'space']
words['There', 'Are', 'Few', 'Wise', 'Words']
" ".join(words) # join method on string expects a list of strings'There Are Few Wise Words'
"-".join(words)'There-Are-Few-Wise-Words'
",".join(words)'There,Are,Few,Wise,Words'
morewords = dashed.split("-")morewords['This',
'is',
'another',
'text',
'with',
'dash',
'in',
'it',
'instead',
'of',
'space']
",".join(morewords[:3]) 'This,is,another'
",".join(morewords[:3]) + "-".join(morewords[3:])'This,is,anothertext-with-dash-in-it-instead-of-space'
def join_with_comma_dash(words, n):
return ",".join(words[:n]) + "-".join(words[n:])join_with_comma_dash(morewords, 5)'This,is,another,text,withdash-in-it-instead-of-space'
join_with_comma_dash(morewords, 8)'This,is,another,text,with,dash,in,itinstead-of-space'
def join_with_comma_dash(words, n):
return ",".join(words[:n]) + "|" + "-".join(words[n:])join_with_comma_dash(morewords, 6)'This,is,another,text,with,dash|in-it-instead-of-space'
"hello" + "world"'helloworld'
def join_with_comma_dash(words, n):
return "|".join([",".join(words[:n]) ,
"-".join(words[n:])])join_with_comma_dash(morewords, 6)'This,is,another,text,with,dash|in-it-instead-of-space'
def join_with_comma_dash(words, n):
return ",".join(words[:n]) + "|" + "-".join(words[n:])words['There', 'Are', 'Few', 'Wise', 'Words']
morewords['This',
'is',
'another',
'text',
'with',
'dash',
'in',
'it',
'instead',
'of',
'space']
morewords[:5]['This', 'is', 'another', 'text', 'with']
morewords[5:]['dash', 'in', 'it', 'instead', 'of', 'space']
morewords[4:]['with', 'dash', 'in', 'it', 'instead', 'of', 'space']
List methods
List has methods to find items. these methods return!
nums = [1, 2, 3, 4]nums.index(3)2
X = [1, 2, 3, 3, 3, 5, 6]X.index(3) # it will give occurence2
words['There', 'Are', 'Few', 'Wise', 'Words']
words.index("There")0
words.index("Few")2
words.index("what")ValueError: 'what' is not in list
ones = [1, 1, 1, 1, 1, 1, 1]ones.count(1)7
Mehtod to add new items in the list. These methods do not return but change the original list
empty = []empty.append(1) # it will not return any value, but it will change original listempty[1]
empty.append(2)empty[1, 2]
empty.append(5)empty[1, 2, 5]
empty.insert(0, 23) # at location 0 insert 23empty[23, 1, 2, 5]
empty.remove(23)empty.insert(0, 24)empty[24, 1, 2, 5]
empty.clear() # will delete all items from the list empty[]
ones = [1, 1, 1]
twos = [2, 2, 2]ones.extend(twos) # add all items from second list into first one ..at endones[1, 1, 1, 2, 2, 2]
twos[2, 2, 2]
nums = [232, 4332, 12, 3, 2, 43]sorted(nums) # will sort the list and will return a list[2, 3, 12, 43, 232, 4332]
nums.sort() # method ... will sort the list inplace. we will loose the original listnums[2, 3, 12, 43, 232, 4332]
sorted(nums, reverse=True)[4332, 232, 43, 12, 3, 2]
nums.sort(reverse=True)nums[4332, 232, 43, 12, 3, 2]
ones.extend(2)TypeError: 'int' object is not iterable
ones.extend("text") # this will take very char from "text" and put as a seperate item in onesones[1, 1, 1, 2, 2, 2, 't', 'e', 'x', 't']
sorted("Let me sort these chars")[' ',
' ',
' ',
' ',
'L',
'a',
'c',
'e',
'e',
'e',
'e',
'h',
'h',
'm',
'o',
'r',
'r',
's',
's',
's',
't',
't',
't']
def sorttext(text):
return "".join(sorted(text))sorttext("LET us sort htis out")' ELThioorssstttuu'
%load_problem numeric_valueIn financial terms a negative balance is represented with round barackets around the number instead of - sign. Write a function numeric_value which returns actual numeric value. For example a value "(1234)" should get -1234 as numeric value. while "34" will get value as 34
>>> numeric_value("(1234)")
-1234
>>> numeric_value("42")
42
You can verify your solution using:
%verify_problem numeric_value
# your code here
%load_problem reverse_digitsWrite a function reverse_digits which will reverse digits of multi digit number and return new formed integer.
>>> reverse_digits(1234)
4321
You can verify your solution using:
%verify_problem reverse_digits
# your code here