TA1107 - Jupyter Notebook

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 12

TA1110_1111

Written and Edited by Dio H.


#@@ Codes didn't appear in class or in PPT.

0. Quiz: Hard one


In [184]: #第一格答案
print('-------第一格答案-------')
#題目
md={'a':1}
for i in md.items():
print(type(i))

#第一格說明
print('-------第一格說明-------')
#x.items() #->returns a list of tuple
print(md.items()) #-> 印出來長這樣 dict_items([('a', 1)]) ,又 for i in md.items(): 代表 對這個list中的每個elements(即



#第二格答案
print('-------第二格答案-------')
#題目
md={'a':1}
for i in md.values():
print(type(i))

#第二格說明
#print('-------第二格說明-------')
#即獲得dictionary中所有的值



#第三格答案
print('-------第三格答案-------')
#題目
md={'a':1}
for i in md.keys():
print(type(i))

#第三格說明
#print('-------第三格說明-------')
#即獲得dictionary中所有的key



#第四格答案
print('-------第四格答案-------')
#題目
print(type(md))

#第四格說明
#print('-------第四格說明-------')
#md 就是一個dictionary

-------第一格答案-------

<class 'tuple'>

-------第一格說明-------

dict_items([('a', 1)])

-------第二格答案-------

<class 'int'>

-------第三格答案-------

<class 'str'>

-------第四格答案-------

<class 'dict'>

1.Set
Type of collection.
Does not allow repeated item.
Is unorderd.
Similar to list but have a curly brackets{大括號}
Similar to dictionary but don't have key

1.1 Create Set

In [3]: # empty set


s=set()
print(s)
print(type(s))

set()

<class 'set'>

1.2 List <-> Set, String -> List VS String -> Set

In [190]: #List -> Set


# [1,2,3] is a list
print(type([1,2,3]))
s1=set([1,2,3])
print(s1) #Similar to list but have a curly brackets{大括號}
print(type(s1))

print('--------------')
# set -> list
# {1,2,3} is a set
print(type({1,2,3}))
s1=list({1,2,3})
print(s1)
print(type(s1))

<class 'list'>

{1, 2, 3}

<class 'set'>

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

<class 'set'>

[1, 2, 3]

<class 'list'>

In [193]: # string -> list


a_list=list('good')
print(a_list)
print(type(a_list))

#VS

print('--------------------')
# string -> set
b=set("good")
print(b)
print(type(b))

['g', 'o', 'o', 'd']

<class 'list'>

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

{'d', 'o', 'g'}

<class 'set'>

1.3 Use of Set

In [195]: #Remove repeated items


lst=[1,1,1,2,2,2,2,2,3,3,3,4,4,5]
myset=set(lst)
print(myset)

{1, 2, 3, 4, 5}

1.4 Intersection, Union, Difference


In [ ]: s1=set([1,2,3,4])
s2=set([3,4,5,6])

#Intersection
print(s1&s2)
print(s1.intersection(s2))
print(s2.intersection(s1))

print("-------------------------")
#uion
print(s1|s2) # | means or
print(s1.union(s2))
print(s2.union(s1))

print("-------------------------")
# difference
print(s1-s2)
print(s1.difference(s2))

print(s2-s1)
print(s2.difference(s1))

{3, 4}

{3, 4}

{3, 4}

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

{1, 2, 3, 4, 5, 6}

{1, 2, 3, 4, 5, 6}

{1, 2, 3, 4, 5, 6}

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

{1, 2}

{1, 2}

{5, 6}

{5, 6}

x.add(), x.update(), x.remove()

In [13]: # Check our smaple


s1={1,2,3,4}
print(s1)

#Let's check what we can do to set
#dir(s1)

{1, 2, 3, 4}

In [14]: s1.add(5)
print(s1)

{1, 2, 3, 4, 5}

In [34]: s1.add('apple')
print(s1)

{1, 2, 3, 4, 5, 'apple'}

In [35]: # 4 NOT added due to 4 is already exists


s1.add(4)
print(s1)

{1, 2, 3, 4, 5, 'apple'}

In [36]: # add() takes exactly one argument


#s1.add(10,11)
#print(s1)

#through x.update() 可以一次新增很多
s1.update([10,11,12])
print(s1)

print('------------------------------------------')
s1.update([1,2,8,9]) #已有的值不再新增
print(s1)

{1, 2, 3, 4, 5, 10, 11, 12, 'apple'}

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

{1, 2, 3, 4, 5, 8, 9, 10, 11, 12, 'apple'}

In [37]: s1.remove("apple")
print(s1)

{1, 2, 3, 4, 5, 8, 9, 10, 11, 12}

In [38]: s1.remove(1)
print(s1)

{2, 3, 4, 5, 8, 9, 10, 11, 12}

2. Bool
Have only two Values: True, False

In [39]: print(type(False))
print(type(True))

<class 'bool'>

<class 'bool'>

In [17]: print(2>1)
print(type(2>1))

print('--------------')
print(2==1)
print(type(2==1))

True

<class 'bool'>

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

False

<class 'bool'>

3.File

3.-1 Before File, let's review newline (\n)


In [110]: alph ='A\nB\nC\n'
print(alph)

print('---')
print(len(alph))
# A\nB\nC\n
#len 1 23 45 6

print('-------------')
print(type(alph))

---

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

<class 'str'>

3.0 Create a new txt


use Word and save as .txt
用 文字編輯 然後隨便打打東西儲存,找到該檔案並在後面加上.txt,然後打開來修改裡面的內容
Using codes as below

In [1]: with open('TA1110_1111_temp.txt', 'w') as newfile:


newfile.write('Hello world!\n')
newfile.write('Goodbye world!\n')

In [2]: with open('Example.txt', 'w') as newfile:


newfile.write('This is line 1\n')
newfile.write('This is line 2\n')
newfile.write('This is line 3\n')

3.1 Open a file


file = open("file path and file name", "mode")
mode
r -> Read a file (default) 讀取檔案
w -> Write a file, truncate a file first
a -> Append a file if exists

In [27]: #help(open)

file=open('Example.txt','r')
print(file) #只顯示讀檔狀態
#dir(file)

<_io.TextIOWrapper name='Example.txt' mode='r' encoding='UTF-8'>

In [28]: #Check file name and mode


print(file.name)
print(file.mode)

Example.txt

3.2 Read a file


U may ignore file path if u put file and code in the same folder
Method1: x.read() 把檔案有啥顯示出來
Method2(better), Pls ignore the symbols below, it's code:
with open("file path and name", "mode") as x:
xcontent=x.read()
print(xcontent)
In [25]: #Method1:
file=open('Example.txt','r')
filecontent=file.read()
filecontent #不換行,且有\n

#VS next cell

Out[25]: 'This is line 1\nThis is line 2\nThis is line 3\n'

In [26]: print(filecontent) #會換行,且無\n


print(type(filecontent))

This is line 1

This is line 2

This is line 3

<class 'str'>

In [27]: #Method2:
#a better way to read fille
with open('Example.txt', 'r') as file1:
file1content=file1.read()
print(file1content)

This is line 1

This is line 2

This is line 3

In [28]: #Without setting a variable


with open('Example.txt', 'r') as file2:
print(file2.read())

This is line 1

This is line 2

This is line 3

3.2.1 Things we can put in x.read()

We can put numbers inside ()

In [29]: # This is line 1\nThis is line 2\nThis is line 3


# 12341234123456 12345123456789
# 因\n為起始,故這裡的\n變成了換行 所以印出空行
with open('Example.txt', 'r') as file2:
print(file2.read(4)) # It will show the first 4 characters
print('-------')
print(file2.read(4)) # When read again, it will show the next 4 characters
print('-------')
print(file2.read(6)) # When read again, it will show the next 6 characters
print('-------')
print(file2.read(5)) # When read again, it will show the next 5 characters

This

-------

is

-------

line 1

-------

This

In [10]: #This is line 1\nThis is line 2\nThis is line 3


#12345612345612 345678910123456
# 因\n非為起始,雖這裡的\n變成了換行 但不印出空行

with open('Example.txt', 'r') as file2:
print(file2.read(6))
print(file2.read(6))
print(file2.read(10))
print(file2.read(6))

This i

s line

This is

line

3.2.2 x.readline()

Read the first line

In [11]: #Method1
with open('Example.txt', 'r') as file:
print(file.readline())

This is line 1

In [12]: #Method2
file3=open('Example.txt', 'r')
file3.readline()

#VS next cell

Out[12]: 'This is line 1\n'

In [32]: file3=open('Example.txt', 'r')


print(file3.readline())

This is line 1

3.2.3 x.readlines()

read all lines


return a list with stings inside, one row one string elements

In [33]: file4=open('Example.txt', 'r').readlines()


print(file4)

#Check data type
print(type(file4))

['This is line 1\n', 'This is line 2\n', 'This is line 3\n']

<class 'list'>

In [17]: #Can also using slice, hence it's a list


print(file4[0])
print(file4[1])

#VS next cell and nextnext cell

This is line 1

This is line 2

In [22]: file4[0]

Out[22]: 'This is line 1\n'


In [20]: file4[1]

Out[20]: 'This is line 2\n'

3.3 Close the file after finishing


x.close()

In [34]: file.close()

3.4 Comapre1: open(), open().read(), open readlines()

In [44]: #case1
# fh=open("TA1110_1111_temp.txt", 'r') #亦可
path="TA1110_1111_temp.txt"
fh=open(path, 'r') #即使不寫'r'也可以,這個r電腦要讀取檔案
print(fh)
#VS next cell

<_io.TextIOWrapper name='TA1110_1111_temp.txt' mode='r' encoding='UTF-8'>

In [45]: #without print function


fh #same as above

Out[45]: <_io.TextIOWrapper name='TA1110_1111_temp.txt' mode='r' encoding='UTF-8'>

In [53]: #case2
#fh2=open("TA1110_1111_temp.txt", 'r').read()
fh2=open(path).read() #-> return strings 這個read是要把他念出來的感覺
print(fh2) #為何有空行?因最後有換行符號
print(type(fh2))

#VS next cell

Hello world!

Goodbye world!

<class 'str'>

In [47]: #without print function


fh2 #different with above

Out[47]: 'Hello world!\nGoodbye world!\n'

In [48]: #case 3
#fh3=open("TA1110_1111_temp.txt", 'r').readlines()
fh3=open(path).readlines() #-> return list
print(fh3)
print(type(fh3))
print(fh3[0]) #為何有空行?因最後有換行符號
print(fh3[1]) #為何有空行?因最後有換行符號

#VS next cell

['Hello world!\n', 'Goodbye world!\n']

<class 'list'>

Hello world!

Goodbye world!

In [146]: #without print function


fh3[0] #different with above

Out[146]: 'Hello world!\n'


In [54]: #without print function
fh3[1] #different with above

Out[54]: 'Goodbye world!\n'

3.5 Comapre2: open(), open().read(), open readlines()

In [56]: #case1
path="TA1110_1111_intro-short.txt"
fh=open(path, 'r') #即使不寫'r'也可以
print(fh)

<_io.TextIOWrapper name='TA1110_1111_intro-short.txt' mode='r' encoding='UTF-8'>

In [57]: #case2
fh2=open(path).read() #->print strings
print(fh2)
print(type)

#亦可
#with open ('TA1110_1111_intro-short.txt') as c2_1:
#print(c2_1.read())

Why should you learn to write programs?

Writing programs (or programming) is a very creative

and rewarding activity. You can write programs for

many reasons, ranging from making your living to solving

a difficult data analysis problem to having fun to helping

someone else solve a problem. This book assumes that

everyone needs to know how to program, and that once

you know how to program you will figure out what you want

to do with your newfound skills.

<class 'type'>

In [59]: #case 3
fh3=open(path).readlines() #->print list
print(fh3)
print(type(fh3))
print(fh3[0])
print(fh3[1])

#亦可
#with open ('TA1110_1111_intro-short.txt') as c3_2:
#print(c3_2.readlines())

['Why should you learn to write programs?\n', '\n', 'Writing programs (or programming) is a very creative \n',
'and rewarding activity. You can write programs for \n', 'many reasons, ranging from making your living to solv
ing\n', 'a difficult data analysis problem to having fun to helping\n', 'someone else solve a problem. This boo
k assumes that \n', 'everyone needs to know how to program, and that once \n', 'you know how to program you will
figure out what you want \n', 'to do with your newfound skills. \n']

<class 'list'>

Why should you learn to write programs?

In [ ]: #case3
with open ('TA1110_1111_intro-short.txt') as c3_3:
a=c3_3.readlines()
print(a)

# ['Why should you learn to write programs?\n', '\n', 'Writing programs (or programming) is a very creative
# Index 0 1 2
print('------------------------------------')
print(a[2]) #為何有空行?因最後有換行符號
print('------------------------------------')
print(a[1]) #為何是空行,因為是換行符號
#VS next cell
print('------------------------------------')

['Why should you learn to write programs?\n', '\n', 'Writing programs (or programming) is a very creative \n',
'and rewarding activity. You can write programs for \n', 'many reasons, ranging from making your living to solv
ing\n', 'a difficult data analysis problem to having fun to helping\n', 'someone else solve a problem. This boo
k assumes that \n', 'everyone needs to know how to program, and that once \n', 'you know how to program you will
figure out what you want \n', 'to do with your newfound skills. \n']

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

Writing programs (or programming) is a very creative

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

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

In [79]: #without print function


a[1] #different with above

Out[79]: '\n'

3.6 Read the file line by (for loop)


In [96]: with open('TA1110_1111_temp.txt') as file:
for i in file:
print(i) # 因為有\n所以有空行

print('------------------------------------------------------------')
#空行變不見法1
with open('TA1110_1111_temp.txt') as file:
for i in file:
print(i.rstrip()) # 刪除字串右邊的空白

print('------------------------------------------------------------')
#空行變不見法2
with open('TA1110_1111_temp.txt', 'r') as f1:
for line in f1:
print(line.strip()) #刪除字串頭尾空白

print('------------------------------------------------------------')
#特別留意純空行\n不會被刪除
with open('TA1110_1111_intro-short.txt', 'r') as f1:
for line in f1:
print(line.strip())

Hello world!

Goodbye world!

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

Hello world!

Goodbye world!

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

Hello world!

Goodbye world!

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

Why should you learn to write programs?

Writing programs (or programming) is a very creative

and rewarding activity. You can write programs for

many reasons, ranging from making your living to solving

a difficult data analysis problem to having fun to helping

someone else solve a problem. This book assumes that

everyone needs to know how to program, and that once

you know how to program you will figure out what you want

to do with your newfound skills.

In [47]: #運用字串格式化,增添點字
with open('TA1110_1111_temp.txt') as f1:
i=1
for sen in f1:
print('line %d' %i, sen) #舊式字串格式化
i=i+1

line 1 Hello world!

line 2 Goodbye world!

In [164]: with open('TA1110_1111_intro-short.txt') as f1:


i=1
for sen in f1:
print('line %d' %i, sen) #舊式字串格式化
i=i+1

line 1 Why should you learn to write programs?

line 2

line 3 Writing programs (or programming) is a very creative

line 4 and rewarding activity. You can write programs for

line 5 many reasons, ranging from making your living to solving

line 6 a difficult data analysis problem to having fun to helping

line 7 someone else solve a problem. This book assumes that

line 8 everyone needs to know how to program, and that once

line 9 you know how to program you will figure out what you want

line 10 to do with your newfound skills.

In [36]: #如果我不要空行
with open('TA1110_1111_intro-short.txt') as f1:
i=1
for sen in f1:
x=f'line {i}: {sen}' #新式字串格式化
print(x.rstrip()) #搭配這個,刪除換行,因為他是字串的尾吧空白
i=i+1

line 1: Why should you learn to write programs?

line 2:

line 3: Writing programs (or programming) is a very creative

line 4: and rewarding activity. You can write programs for

line 5: many reasons, ranging from making your living to solving

line 6: a difficult data analysis problem to having fun to helping

line 7: someone else solve a problem. This book assumes that

line 8: everyone needs to know how to program, and that once

line 9: you know how to program you will figure out what you want

line 10: to do with your newfound skills.

End of Class

In [ ]: ​

You might also like