1. 程式人生 > >Python總結——Python基礎

Python總結——Python基礎

總結

 1、註釋

單行註釋:#

多行註釋:''' '''  ,  """ """

2、資料型別

  • Number : 數字型別 (int , float ,    bool    , complex)

                              eg:         1  ,  1.0  , True/False ,   1+1j

  • String: 字串  

                              eg:'' , 'abc'

  • List:   列表    

                             eg:[] , [1,2,3]

  • Tuple:  元組    

                            eg:tuple() , (1,2) ,(1,)

  • Set:    集合

                           eg:set() , {1,2,3,'4'}

  • Dictionary:字典 

                            eg:{} , {1:2,'a':5}

3、序列(sequence):String , List , Tuple

序列也是有序序列,序列可以使用序列方法,比如:[1::-1]切片操作,通過下標索引訪問
 

list1 = [1,2,3,4]
print(list1[1:2])
print(list1[1])

tuple1 = (1,2,3,4)
print(tuple1[1::2])
print(tuple[2])

str1 = 'abcdef'
print(str1[1:3])
print(str[1:])

#result:
# [2]
# 2
# (2, 4)
# 3
# bc
# bcdef

4、型別轉換( int , float , bool , complex , str , list , tuple , dict )

# int , float , bool , complex  , str , list , tuple , dict
#-----------型別轉換------------------
#all->str
print('==============all->str==================')
print('int-->str:',str(1))
print('complex-->str:',str(1+1j))
print('bool-->str:',str(True))
print('list-->str:',str([1,2,3]))
print('tuple-->str:',str((1,2,3)))
print('set-->str:',str({1,2,3}))
print('dict-->str:',str({1:2,2:3}))
#res:
# int-->str: 1
# complex-->str: (1+1j)
# bool-->str: True
# list-->str: [1, 2, 3]
# tuple-->str: (1, 2, 3)
# set-->str: {1, 2, 3}
# dict-->str: {1: 2, 2: 3}

#all-->list
print('==============all-->list==================')
print('int-->list:轉換不了')
print('str-->list:',list('abc'))
print('tuple-->list:',list((1,2,3)))
print('set-->list:',list({1,2,3}))
print('dict-->list:',list({1:2,2:3,'a':'b'})) #只輸出key組成的list
# int-->list:轉換不了
# str-->list: ['a', 'b', 'c']
# tuple-->list: [1, 2, 3]
# set-->list: [1, 2, 3]
# dict-->list: [1, 2, 'a']

#all-->tuple
print('========all-->tuple:和all-->list一樣======')
#all-->set
print('=========all-->set:和all-->list一樣========')

#all-->dict
print('===all-->dict:每個元素必須是成對出現的可迭代物件才可轉換====')
print('list-->dict:',dict([(1,2),[3,4]]))
print('tuple-->dict:',dict(((1,2),[3,4])))
print(dict(zip([1,2,3],(2,3,5))))
# list-->dict: {1: 2, 3: 4}
# tuple-->dict: {1: 2, 3: 4}
# {1: 2, 2: 3, 3: 5}


#all --> int
print(int('   5   '))
print(int('   00500 '))
#error:print(int('   005 00 '))  #因為方法內部先呼叫trim(),然後轉int,‘5 00’肯定就轉不了int
print(int(True))
print(int(False))
# error:print(int(1+2j))  #錯誤,不能將complex轉換為int
# 不能轉列表,元組,集合和字典

5、運算子

算數運算子
+ , - , * , / , // , % , **


比較運算子
== , != , > , < , >= , <=


賦值運算子
= , += , -= , *= , /= , %= , **= , //=

位運算子
& , | , ^ , ~ , << , >>

邏輯運算子(返回True/False)
and  ,  or  , not

成員運算子(返回值為True/False)
in , not in

 

練習:

# ======================算數運算子===========================
# + , - , * , / , // , % , **
print(1 + 2)    3
#序列的拼接,集合和字典沒有加法運算子
print([1,2] + ['a',3])    [1, 2, 'a', 3]
print('123' + 'abc')    123abc
print((1,2,3) + (4,5,6))    (1, 2, 3, 4, 5, 6)

#減法運算子    
print(1 - 2)    -1
print({1,2,3}-{1,5,6})    {2, 3} #集合可以進行-(去掉相同的元素),&(集合的並集) ,|(集合元素的和)運算

#乘法運算子,序列*n
print(1 * 5)    5
print('abc'*2)    abcabc
print((1,2)*2)    (1, 2, 1, 2)
print([1,2,3]*2)    [1, 2, 3, 1, 2, 3]

#商值取整數,記住是向下取整
print(1/2)   	0.5
print(-1/2)    -0.5
print(-1 % 2)	1
print(1 % -2)	-1

#取商值
print(5 / 2)    2.5



#取模
print(-5 % 2)   1 #對於負數的值為:除數-被除數*商   

#取值的次方
print(5**2)    25
print(16**(1/2))    4.0  #float型別



# ======================比較運算子===========================

print(1>2)    True
print(True == 1)    True
print(False == 0)    False
print(2 != 2)    False
print(True > 1j) Error #bool和complex不能進行比較,貌似複數和任何型別都不能進行>,<比較,==可以


print(3>2>2)    False
print('abc'>'xyz')    False
print((3,2)>(1,2))    True
print(1>'2')     Error:報錯 TypeError: '>' not supported between instances of 
                        'int' and 'str'
print((3,2)>('a','b'))  Error:同上
print((3,2)>(2,'b'))   True
print((3,2)>(3,'b'))    Error:同上
#--->所以有沒有發現:不同型別之間不能進行比較(Number內部可以進行比較)


# ======================賦值運算子===========================

a = 5
a += 1  6
a -= 2  4
a *= 2  8
a /= 2  4
a %= 2  2
a **= 2 4
a //= 2 2


# ======================邏輯運算子===========================
# and  ,  or  , not
print('=========')
print( True and False)  False
print( 5 > 3 and 3< 5)  True
print(5>3>5)    False #相當於 5>3 and 3>5

>>> 4 and 5
5
>>> 1 or 9
1
>>> not 4
False
>>> not 0
True
>>> 0 and 4
0

# ======================成員運算子===========================
# in , not in
print(1 in [1,2])   True
print( 'a' not in (1,2,3))  True

6、

if <條件判斷1>:
    <執行1>
elif <條件判斷2>:
    <執行2>
elif <條件判斷3>:
    <執行3>
else:
    <執行4>
age = 20
if age >= 6:
    print('teenager')
elif age >= 18:
    print('adult')
else:
    print('kid')


​#這兒條件相當於bool(x)
if x:
    print('True')

​

 7、迴圈語句

Python的迴圈有兩種,一種是for...in迴圈,依次把list或tuple中的每個元素迭代出來,看例子:

names = ['Michael', 'Bob', 'Tracy']
for name in names:
    print(name)

 執行這段程式碼,會依次列印names的每一個元素:

Michael
Bob
Tracy

 Test:

 list(range(5))
 #res:[0, 1, 2, 3, 4]

另外一種迴圈就是while迴圈了

#迴圈輸出1到20的數
count = 0
while count < 20:
    count += 1
    print(count) 
else:
    print('ok')