python入門筆記(資料操作)
str_string = "中國人"#則str自動為string型別資料
int_int = 342
float_float=100.2
#2、Python查詢資料型別
print(type(str_string))
print(type(int_int))
print(type(float_float))
#資料轉換
string="123"
intt=124
floatt=123.4
int_type=int(string)
string_type=str(intt)
print(type(int_type))
print(type(string_type))
#資料計算
j=2
y=3
h=j+y
jian=y-j
c=j*y
chu=j/y
ercimi=j**y#二次冪2的3次方等於8
print(ercimi)
#list資料
months=[]#定義list型別
print(type(months))
months.append("1月")#向list中新增資料
months.append(2)
months.append(21.02)
months.append(22.02)
months.append(23.02)
months.append(24.02)
print(months)
#list索引取值
index=months[0]
print(index)
index1=months[1]
print(index1)
index2=months[2]
print(index2)
#查詢list資料長度
length=len(months)
print(length)
#查詢list最後一個值
lastindex=months[length-1]
print(lastindex)
#查詢list中的某一段連續值
list_duan=months[2:4]#第三個和第四個值
print(list_duan)
#從某個元素開始取後面所有的值
six=months[3:]#第三個以及以後的所有值
print(six)
#for迴圈
counts=[1,2,3,4,5,6,7]
for count in counts:
print(count)
#while迴圈
i=0
while i<3:
i+=1
print(i)
#for迴圈另一種寫法
for i in range(10):
print(i)
#迴圈list of list
months=[["我","是","中","國","人"],[1,2,3,4,5,6,7]]
for month in months:
for i in month:
print(i)
#bool變數值
bool_bool=True
print(type(bool_bool))
print(8==8)
print(8==10)
print(8!=10)
print(["中","國"]==["國","中"])
#判斷if語句
i=30
j=5
if (i<j):
print(j)
else:
print(i)
#在list中尋找某個元素
months=[0,1,2,3,4,5,6,7,8,9]
if 1 in months:
print("Get it !")
#字典結構
scores={}#key value,定義字典結構
print(type(scores))
scores["A"]=0
scores["B"]=1
scores["C"]=2
scores["D"]=3
scores["E"]=4
scores["F"]=5
print(scores.keys())
print(scores)
print(scores["B"])#B的值為1
#判斷元素是否在字典裡
students={"A":0,"B":1,"C":2}
print("B" in students)#判斷B是否在字典裡
#判斷元素在字典中出現了幾次
frult=["A","B","C","D","E","F","G","H","I","J","B"]
frult_counts={}
for item in frult:
if item in frult_counts:
frult_counts[item]=frult_counts[item]+1
else:
frult_counts[item]=1
print(frult_counts)
#檔案操作
f=open("test.txt","r")#開啟文件
g=f.read()#讀取文件
print(g)#操作文件
f.close()#關閉文件
#寫檔案
f=open("write_txt.txt","w")
f.write("我")
f.write("是")
f.write("中")
f.write("國")
f.write("人")
f.write("\n")#換行
f.write("12345")
f.close()
#csv檔案操作
r_data=[]
f=open("test.csv","r")
data=f.read()
rows=data.split("\n")
for row in rows:
split_row=row.split(",")
r_data.append(split_row)
print(r_data)
#顯示第幾列
name=[]
for row in r_data:
name.append(row[0])
print (name)
f.close()
#定義函式
def printhello():
print("hello!")
printhello()
def printnum():
for i in range(0,4):
print(i)
return
printnum()
def add(a,b):
return(a-b)
print(add(5,3))