1. 程式人生 > >Python程式設計基礎

Python程式設計基礎

Python入門基礎知識

1. Python資料基本結構

Python的資料是弱型別,使用一個變數前不必提前宣告。

1.1. 字串

string =  "this is a string!" #單引號可代替雙引號
print(string)
this is a string!
string_new = 'this is a ""' 
print(string_new)
this is a ""
print("my name is %s" %"jok")
my name is jok

1.2. 數值

int_num = 9 #整形
float_num = 9.111111
#浮點型 print(int_num,float_num,int(9.9999),int_num == int(float_num))
9 9.111111 9 True

1.3.布林型別

print(1>2,2>1,True == False,True == 1)
False True False True

1.4. 空值

list_None = [1,2,3,None,4]
i = 0
while list_None[i] != None:
    print(list_None[i])
    i +=1
1
2
3

1.5. 列表

list1 = ["zhangsan","1",2,None,1>2] #建立一個列表,其中的資料型別,可以是任意型別
print(list1)
['zhangsan', '1', 2, None, False]
print(len(list1)) #輸出列表長度
type(list1) #輸出變數的型別
4
list
list2 = [1,2,list1] #列表內也可以是另外一個列表
print(list2)
[1, 2, ['zhangsan', '1', 2, None, False]]
list1.remove('zhangsan') # 刪除'zhangsan' 作用等同於  del list1[0]
print(list1)
['1', 2, None, False]
list1.reverse() # 反向輸出
print(list1)
[False, None, 2, '1']
print(list2) #當我們改變list1時,list2也在同時發生改變
[1, 2, ['1', 2, None, False]]
list2[2][0] = 2 #修改元素值
print("list2:{}".format(list2)) #當我們改變list2中的list1的內容時,發現list1並沒有被改變
print("list1:{}".format(list1))
list2:[1, 2, [2, 2, None, False]]
list1:[False, None, 2, '1']
a =  [1,2,3,[4,5,6]]
b = a
print("a的地址為{},b的地址為{}".format(id(a),id(b)))
a的地址為78568968,b的地址為78568968

1.6. 元組

tuple_new = (1,2,3,4)
print(tuple_new,type(tuple_new))
(1, 2, 3, 4) <class 'tuple'>
print(tuple_new[0])
tuple_new[0] = 5   #元組tuple型別不支援修改值
print(tuple_new)
1



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

TypeError                                 Traceback (most recent call last)

<ipython-input-5-f8420301967a> in <module>()
      1 print(tuple_new[0])
----> 2 tuple_new[0] = 5   #元組tuple型別不支援修改值
      3 print(tuple_new)


TypeError: 'tuple' object does not support item assignment

1.7. 集合

set_new = {1,2,7,4,1}
print(set_new) # 集合會自動的呼叫去重與排序演算法
{1, 2, 4, 7}
set_new.update([10])  #集合元素的新增
set_new.add(0)
print(set_new) 
{0, 1, 2, 4, 7, 10}
set_new = {4,3,2,1}
set_new.pop()
print(set_new) #去掉第一個元素(排序後的元素)
{2, 3, 4}
set_new.discard(3) # 去掉值為3的元素
print(set_new)
{2, 4}
print(2 in set_new) #判斷2是否在集合set_new中
True

1.8. 字典

dict_new = {'name':'job','age':'55','state':'diey'}
print(dict_new)
{'name': 'job', 'age': '55', 'state': 'diey'}
print(dict_new['age']) #按照key取值
55
dict_new['age']=66 #修改值
del dict_new['state'] #刪除元素
print(dict_new)
{'name': 'job', 'age': 66}
dict_nem = {1:2,(2,2):3,[3]:4} #因為字典的key不可變,所以不能使用list來充當key
---------------------------------------------------------------------------

TypeError                                 Traceback (most recent call last)

<ipython-input-40-f7209f4288fd> in <module>()
----> 1 dict_nem = {1:2,(2,2):3,[3]:4}


TypeError: unhashable type: 'list'

未完待續--條件、迴圈