You are on page 1of 13

TA1006_1007

Edited and Written by Dio H.

1. More things about Function that we define by owerself.

1.1 When should I put a return ? pls check the following 2 codes. #@@

In [1]: def addition(a,b):#@@


return a+b
addition(1,2)
# This is saying that function addition will add a and b and return it, so that we can see 3.

Out[1]: 3

In [2]: def addition(a,b):#@@


print(a+b)
addition(1,2)
#This is saying that function addition will print something, and this somethings is a + b.

1.2 Codes of Functions for this week

1.2.1 Create dictionary by using **

In [3]: #{key : value}


def dic(**kv):#define function
return kv# kv is just a variable u may chnage into whatever u like
dic(apple=2,banana=5,orange=3)#call the function

Out[3]: {'apple': 2, 'banana': 5, 'orange': 3}

In [4]: # put Quotation marks if u want to enter string


dic(name='Dio',age=20,school='NCCU')

Out[4]: {'name': 'Dio', 'age': 20, 'school': 'NCCU'}

1.2.2 Another usage of return

In [5]: def say1(nick):# %s is for string or number, %d is for number.


print('My nickname is',nick+'.')
print(f'My nickname is {nick}.')
print('My nickname is %s.'%nick)
#因為沒有要回傳任何變數,固無不可放return。 #@@
say1('pig')
print("----------------------")
say1('1004')# it's a string

My nickname is pig.

My nickname is pig.

My nickname is pig.

----------------------

My nickname is 1004.

My nickname is 1004.

My nickname is 1004.

In [19]: #say1(1004) #we can't connect stings and number by using +


def say2(nick):
print('My nickname is',nick,'.')# we can solve it by replace + with , # it will be a blank
print(f'My nickname is {nick}.')
print('My nickname is %s.'%nick) # %s is for string or number, %d is for number.
say2(1004)
#but we will get a blank if we run the first code. It will be good if we use the second or the third code.

My nickname is 1004 .

My nickname is 1004.

My nickname is 1004.

In [27]: def say3(nick):


if nick=='pig':
return
print('My nickname is',nick,'.')
print(f'My nickname is {nick}.')
print('My nickname is %s.'%nick)

In [28]: say3('pig') #due to we only put return, python will not return anything

In [29]: say3('Coco')

My nickname is Coco .

My nickname is Coco.

My nickname is Coco.

In [30]: say3(10)

My nickname is 10 .

My nickname is 10.

My nickname is 10.

In [41]: # set a default value


def say_myself1(name,age,man=True):
print('My name is %s.'%name) #we use %s due to name is string.
print('I am %d years old.'%age) #we use %d due to age is number.
if man==True:
print('I am male.')
else:
print('I am female.')

In [43]: say_myself1('Dio',20) #沒寫就是True



print("----------")
say_myself1('Dio',20,1)#@@ True is 1, False is 0.

print("----------")
say_myself1('Dio',20,True)

My name is Dio.

I am 20 years old.

I am male.

----------

My name is Dio.

I am 20 years old.

I am male.

----------

My name is Dio.

I am 20 years old.

I am male.

In [44]: say_myself1('Dio',20,False)
print("----------")
say_myself1('Dio',20,0) #@@

My name is Dio.

I am 20 years old.

I am female.

----------

My name is Dio.

I am 20 years old.

I am female.

In [45]: # To set a default value, in def we set age=20 and school="NCCU",


# so that if we didn't enter age and school, when call the function Python will still return the default value.
def say_myself2(name,age=20,school='NCCU'):
print('My name is %s.'%name)
print('I am %d years old.'%age)
print('I am a student of %s.'%school)

In [46]: say_myself2('Dio')#Due to we already set default value, so it can print 20 and NCCU automatically.

My name is Dio.

I am 20 years old.

I am a student of NCCU.

In [48]: say_myself2('Dio',27,'NTU')# We can enter what we need if default value is not we want.

My name is Dio.

I am 27 years old.

I am a student of NTU.

1.2.3 What will happen if we put 2 return in code?

In [49]: def add(a,b):


return a+b
return a*b # Nothing happens

add(3,4)

Out[49]: 7

1.2.4 About lambda(匿名函數)

By using lambda we can define our own function in one line.


There is no need to put return in lambda #@@
Can only do one thing #@@

In [53]: #in the past 2 weeks


def add(a,b):
return a+b
add(1,2)

Out[53]: 3

In [54]: # we can do like this


sum=lambda a,b:a+b
sum(1,2)

Out[54]: 3
In [55]: #Ask users for working hours and rate per hour using input() to compute gross pay (hours*rate per hour).
#Use 35 hours and a rate of 2.75 per hour to test the program (the pay should be 96.25).
#You should use input to read a string and float() to convert the string to a number.
hours=float(input('Enter hours:'))
rate=float(input('Enter rate:'))
gross=hours*rate
print('Gross pay:',gross)

Enter hours: 35

Enter rate: 2.75

Gross pay: 96.25

In [56]: gross_pay=lambda a,b:a*b


gross_pay(35,2.75)

Out[56]: 96.25

2. Method
object.method: This week
p.s. Function(object): Before this week

2.1 x.sort
to make items in list small to big in oder.

In [62]: lst1=[1,0,2,4,3,5,7,6,8,10,9]
lst1.sort()
print(lst1)

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

In [64]: lst2=['bananas','apple','cherry']
lst2.sort()
print(lst2)
print("------------------------------")
lst3=['ant','apple','abandon','a']#@@
lst3.sort(key=len)# we can also sort by length of string in list
print(lst3)

['apple', 'bananas', 'cherry']

------------------------------

['a', 'ant', 'apple', 'abandon']

In [68]: lst4=['','?','App','blue','30','!']#@@
lst4.sort()
print(lst4)
#@@ # Why ? is bigger than numbers? Pls check https://zh.wikipedia.org/zh-tw/Unicode字符列表
print("------------------------------------")
print(min(lst4))
print(max(lst4))
#space<!<number<?<capital letter<small letter

['', '!', '30', '?', 'App', 'blue']

------------------------------------

blue

2.2.1 sort vs sorted (Professor Yu haven't talk about this)

sort: changes the list


sorted: only show u what will happen if we sort the list, actually the list didn't change.
In [69]: a=[8,3,4,9,2,0]
a.sort() #Nothing output
print(a)

print("------------------")
b=[8,3,4,9,2,0]
print(sorted(b)) #Try to delete print function and also put a # on the front of next line. U may see an output
print(b) #Nothing changes

[0, 2, 3, 4, 8, 9]

------------------

[0, 2, 3, 4, 8, 9]

[8, 3, 4, 9, 2, 0]

2.2 x.reverse()
This method just show the list backward.

In [1]: lst5=[10,2,5,3,8,1]
lst5.reverse()
lst5

Out[1]: [1, 8, 3, 5, 2, 10]

In [4]: # If we want to get descending order, here are 2 solutions


# 1st Solution
lst5=[10,2,5,3,8,1]

#pre-sort [10,2,5,3,8,1]
lst5.sort()
lst5
print(lst5)
#post-sort [1, 2, 3, 5, 8, 10]
#pre-reverse [1, 2, 3, 5, 8, 10]
lst5.reverse()
#post-reverse [10, 8, 5, 3, 2, 1]
print(lst5)


print("--------------------------------------------------------------------------------------")
# 2nd Solution
help(lst5.sort) #Let's see what sort can do for us. Pls check the last row.
# The reverse flag can be set to sort in descending order.

print("--------------------------------------------------------------------------------------")
lst5=[10,2,5,3,8,1]
lst5.sort(reverse=True)
print(lst5)

[1, 2, 3, 5, 8, 10]

[10, 8, 5, 3, 2, 1]

--------------------------------------------------------------------------------------

Help on built-in function sort:

sort(*, key=None, reverse=False) method of builtins.list instance

Sort the list in ascending order and return None.

The sort is in-place (i.e. the list itself is modified) and stable (i.e. the

order of two equal elements is maintained).

If a key function is given, apply it once to each list item and sort them,

ascending or descending, according to their function values.

The reverse flag can be set to sort in descending order.

--------------------------------------------------------------------------------------

[10, 8, 5, 3, 2, 1]

2.3 x.append()
To put things into list
In [5]: x=[1,2]# we can add a string
x.append('banana')
print(x)

[1, 2, 'banana']

In [6]: x.append(1000) # we can add a number


print(x)

[1, 2, 'banana', 1000]

In [7]: x.append([3,4]) # we can adda list inside a list


print(x)

[1, 2, 'banana', 1000, [3, 4]]

In [8]: x.append('?')# Or even add a ?


print(x)

[1, 2, 'banana', 1000, [3, 4], '?']

In [10]: #Let's check how many items are there in the list.
print(len(x))

# [1, 2, 'banana', 1000, [3, 4], '?']
#index 0 1 2 3 4 5
print(x[4])# To find index 4 in the list

[3, 4]

2.4 x.extend()
Pls put an eye on the difference between append and extend

In [11]: x1=[1,2,3,4]
x1.append('NCCU')
print(x1)
print("--------------------------------")
x2=[1,2,3,4]#If using extend, the string will be seperated.
x2.extend('NCCU')
print(x2)

[1, 2, 3, 4, 'NCCU']

--------------------------------

[1, 2, 3, 4, 'N', 'C', 'C', 'U']

In [12]: x3=[] #create an empty list


x3.extend('NCCU')
print(x3)

['N', 'C', 'C', 'U']

2.5 x.set()
Just like list, but u can't find repeat data.
Pls note that the order in set is random. #@@

In [14]: #help(set(e)) # Pls check row 5.--> Build an unordered collection of unique elements.
x4=[1,2,3,4,'N','C','C','U']
setA=set(x4)
print(type(setA))
print(setA)

<class 'set'>

{1, 2, 3, 4, 'C', 'N', 'U'}

In [16]: #del(setA[0]) we can not delete thing in set, string, tuple


#if we want to delete things, we should change data type. (set->list)
setB=list(setA)
print(setB)
print(type(setB))
print("---------------")
#pre-delete [1, 2, 3, 'N', 4, 'U', 'C']
#index 0 1 2 3 4 5 6
# we can delete now!
#post-delete [2, 3, 'N', 4, 'U', 'C']
#index 0 1 2 3 4 5
del(setB[0])
print(setB)

[1, 2, 3, 4, 'C', 'N', 'U']

<class 'list'>

---------------

[2, 3, 4, 'C', 'N', 'U']

2.6 Three ways to make items disapper in list


del([N]) 用index刪除
x.remove 直接打item name 刪除,若有重複字,會先刪除前面的
x.pop 用index刪除,輸入index後會先顯示要刪的item,再print就會是新的。沒寫index就是刪最後一個

2.6.1 del()

To delete by using index

In [17]: #pre delete


x5=['apple','kiwi','orange','melon']
#index 0 1 2 3
del(x5[1])
print(x5)
# post delete

['apple', 'orange', 'melon']

In [18]: # delete in a range #@@


#pre delete
x6=["apple", "kiwi", "orange", "melon", "tomato", "coconut"]
#index 0 1 2 3 4 5
del(x6[1:3])
print(x6)
# index 1 ~ N-1 is deleted
# post delete

['apple', 'melon', 'tomato', 'coconut']

2.6.2 x.remove

to remove by using an item name


only remove first one if there is more than 1 things in list that u want to remove.

In [83]: x=["apple", "kiwi", "orange", "melon"]


x.remove("kiwi")
print(x)

['apple', 'orange', 'melon']

In [84]: help(x.remove) #@@ #Pls check row 3. -> Remove first occurrence of value.

print("------------------------------------------------------")
a1=["N", "C", "U", "C"]
a1.remove("C") #remove the first "C"
print(a1)

Help on built-in function remove:

remove(value, /) method of builtins.list instance

Remove first occurrence of value.

Raises ValueError if the value is not present.

------------------------------------------------------

['N', 'U', 'C']

2.6.3 x.pop()

It will show which item is popped.


if no index in (), then it will delete the last item.

In [23]: y=[1,2,3,4]

In [28]: help(y.pop) #@@ #Pls check row 3 -> Remove and return item at index (default last).

print("----------------------------------------------------------------------")
y=[1,2,3,4]
print(y.pop()) #Due to the default index is -1, so it will remove and return the last item.
print(y)

Help on built-in function pop:

pop(index=-1, /) method of builtins.list instance

Remove and return item at index (default last).

Raises IndexError if list is empty or index is out of range.

----------------------------------------------------------------------

[1, 2, 3]

In [86]: y=[1,2,3,4]
# [1,2,3,4]
#index 0 1 2 3
print(y.pop(2)) # 2 is index
print(y)

[1, 2, 4]

2.7 x.clear()
clear all itmes

In [87]: x=["apple", "kiwi", "orange", "melon"]


x.clear()
print(x)

[]

2.8 x.index() and x.find()


Pls check the difference.
Diff1: Shows different things when facing not found.

-index找不到的時候會出現type error

-find找不到的時候會出現-1

(兩個都是直接輸入item 找數字定位)
Diff2: We can't use find in list.

In [29]: greet="Good morning"


# Good morning
#index 0123456789..........
print(greet.index(" "))
print(greet.index("o")) #it shows the first one.
#print(greet.index("t")) #Diff1: there will be an error if not found.

print("-----------------")
print(greet.find(" "))
print(greet.find("t")) #Diff1: it shows -1 if not found.
print(greet.find('o'))
print("----------------------------------------------------------------------")
help(greet.find) #@@ #Pls check row 7 -> Return -1 on failure.

-----------------

-1

----------------------------------------------------------------------

Help on built-in function find:

find(...) method of builtins.str instance

S.find(sub[, start[, end]]) -> int

Return the lowest index in S where substring sub is found,

such that sub is contained within S[start:end]. Optional

arguments start and end are interpreted as in slice notation.

Return -1 on failure.

In [89]: x=[1,2,3,4]
# [1,2,3,4]
#index 0 1 2 3
print(x.index(3)) #it means number 3 is at index 2.
#print(x.find(3)) # Diff2: we can't use find in list.

In [2]: x="python"
# python
#index 012345
print(x.find("yt")) #it will only print the location of the first letter.
print(x.index('yt'))

2.9 x.count()
In [9]: email='109353501@g.nccu.edu.tw'
# 109353501@ g . n c c u . e d u . t w (pls ignore the blanks)
#index 0123456789 10 11 12 13 14 15 16 17 18 19 20 21 22

print(email.count('.'))#it will show the number of . is in the string.共有三個'.'
print(email.index('.'))#it will show the first one.找出第一個'.'的數字定位
print(email.find('.'))#it will show the first one.找出第一個'.'的數字定位
#dir(email) #show what we can do with email
print(email.rfind('.'))#it will show the last one.找出最後一個'.'的數字定位
print(email.rindex('.'))#it will show the last one #@@找出最後一個'.'的數字定位

print("--------------------------------------------------------------------")
help(email.rfind)#@@ Show highest index, show -1 when not found
help(email.rindex)#@@ Show highest index, show ValueError when not found.

11

11

20

20

--------------------------------------------------------------------

Help on built-in function rfind:

rfind(...) method of builtins.str instance

S.rfind(sub[, start[, end]]) -> int

Return the highest index in S where substring sub is found,

such that sub is contained within S[start:end]. Optional

arguments start and end are interpreted as in slice notation.

Return -1 on failure.

Help on built-in function rindex:

rindex(...) method of builtins.str instance

S.rindex(sub[, start[, end]]) -> int

Return the highest index in S where substring sub is found,

such that sub is contained within S[start:end]. Optional

arguments start and end are interpreted as in slice notation.

Raises ValueError when the substring is not found.

In [12]: email='109353501@g.nccu.edu.tw'
# show student ID
# [0~N] --> 0 ~ N-1 (即不包含N)
print(email[0:9])
#[:N] --> ~ N-1
print(email[:9])
print("---------------")
# show mail without student ID
# [N:] --> N ~ 從N開始到最後
print(email[9:])
print("---------------")
# show only nccu
# 109353501@ g . n c c u . e d u . t w (pls ignore the blanks)
#indexLV1 0123456789 10 11 12 13 14 15 16 17 18 19 20 21 22
#indexLV2 0 1 2 3 4 5 6 7 8 9 10 11 12 13
print(email[9:][3:7])
print(email[12:16])

109353501

109353501

---------------

@g.nccu.edu.tw

---------------

nccu

nccu

2.10 split() we might can use this when import a txt. file.
In [23]: line='a lot of space'
help(line.split)#@@ #row6 -> None (the default value) means split according to any whitespace.

print("-------------------------------------------------------------------------------")
a=line.split()#split according to any whitespace
print(a)
print("-------------------------------------------------------------------------------")
b=line.split(' ')#@@
print(b)
print("-------------------------------------------------------------------------------")
#@@
#c=line.split("") #Error due to empty separator.
#print(c)

Help on built-in function split:

split(sep=None, maxsplit=-1) method of builtins.str instance

Return a list of the words in the string, using sep as the delimiter string.

sep

The delimiter according which to split the string.

None (the default value) means split according to any whitespace,

and discard empty strings from the result.


maxsplit

Maximum number of splits to do.

-1 (the default value) means no limit.

-------------------------------------------------------------------------------

['a', 'lot', 'of', 'space']

-------------------------------------------------------------------------------

['a', 'lot', 'of', '', '', '', '', 'space']

-------------------------------------------------------------------------------

In [24]: #Let's try differnet sep


day='Mon;Tue;Wed'
print(day.split(';'))
print("--------------------------")
r='I-me-my-mine'
print(r.split('-'))
#@@
print("----------------------------------------------------------------------------------------------------------
data='''公司 簡稱 TSE 產業別 年度 上市狀況 產業別 產業名稱 成立年數 上市年數 事務所碼 簽證事務所 是否
print(data.split())

['Mon', 'Tue', 'Wed']

--------------------------

['I', 'me', 'my', 'mine']

----------------------------------------------------------------------------------------------------------------
-----------------------------------

['公司', '簡稱', 'TSE', '產業別', '年度', '上市狀況', '產業別', '產業名稱', '成立年數', '上市年數', '事務所碼', '簽證
事務所', '是否為大型事務所', '會計師1', '會計師2', '簽證意見類型', '繼續經營假設是否有疑慮', '財報重編次數', '事務所任期
_自1983起(年)', '事務所任期_上市櫃起(年)', '事務所任期_公開發起(年)', 'CPA1任期_自1983起(年)', 'CPA1任期_上市櫃起
(年)', 'CPA1任期_公開發行起(年)', 'CPA2任期_自1983起(年)', 'CPA2任期_上市櫃起(年)', 'CPA2任期_公開發行起(年)', 'CPA1
應輪調', 'CPA2應輪調', 'CPA1連續查核任期', 'CPA2連續查核任期', '更換會計師人數', '更換會計師事務所', '更換會計師事務
所', 'A', 'CPA1經驗_自1983起(年)', 'CPA1經驗_上市櫃(年)', 'CPA1經驗_公開發行(年)', 'CPA1經驗_產業(年)', 'CPA2經驗_自1
983起(年)', 'CPA2經驗_上市櫃(年)', 'CPA2經驗_公開發行(年)', 'CPA2經驗_產業(年)']

In [34]: #we get a list of string


mail='dioh@g.nccu.edu.tw'
a=mail.split('@')
print(a)
print("-------------------------")
#to get fist name and second name
# ["dioh", "g.nccu.edu.tw"]
#index 0 1
print(a[0])
print("-------------------------")
#to get 域名
# ["dioh", "g.nccu.edu.tw"]
#index 0 1
print(a[1])
print("-------------------------")
#to get fist name
# ["dioh", "g.nccu.edu . t w"] (pls ignore the blanks)
#indexLV1 0 1
#indexLV2 0123 0123456789 10 11 12
#index 0 ~ 2(N=3, here doesn't include index 3)
print(a[0][:3])
print(a[0][0:3])
print(a[0][:4])
print(a[0][0:4])

['dioh', 'g.nccu.edu.tw']

-------------------------

dioh

-------------------------

g.nccu.edu.tw

-------------------------

dio

dio

dioh

dioh

In [31]: print("-------------------------")
#to get nccu
# ["dioh", "g.nccu.edu . t w"] (pls ignore the blanks)
#index 0 1
#index 0123 0123456789 10 11 12
print(a[1][2:6])
print("-------------------------")
#to get tw
# ["dioh", "g.nccu.edu . t w"] (pls ignore the blanks)
#indexLV1 0 1
#indexLV1(negative) -2 -1 #@@
#indexLV2 0123 0123456789 10 11 12
#indexLV2(negative) -2 -1 #@@
#index 11 ~ 12(N=13, here doesn't include index 13)
print(a[1][11:13])
print(a[1][11:])
print("-------------------------")
#@@
#to get tw by using negative indexing
print(a[1][-2:])
print(a[-1][-2:])
print(a[-1][11:])
print(a[-1][11:13])

-------------------------

nccu

-------------------------

tw

tw

-------------------------

tw

tw

tw

tw

End of Class

You might also like