python list列表基礎(元組)

GodF發表於2020-12-20

‘’‘元組 不能被修改的列表 []索引’’’
‘’’
tuple = (1,2,3,4,5,6)
print(tuple[2])
3
tuple[2]=100#嘗試修改
print(tuple)
#報錯TypeError
‘’’
‘’‘遍歷元組’’’
‘’‘tuple = (1,2,3,4,5,6)
for i in tuple:
print(i)
1
2
3
4
5
6’’’
‘’‘修改元組變數’’’
‘’‘tuple=(1,2)
for i in tuple:
print(i)
1
2
tuple=(3,4)
for i in tuple:
print(i)
3
4’’’
‘’’
############################################
if 語句 if True/False
‘’’
‘’'cars=[‘audi’,‘bmw’,‘amg’,‘toyota’]

for i in cars:
if i==‘bmw’:
print(i.upper())
else:
print(i)
audi
BMW
amg
toyota’’’
‘’‘car=‘bmw’
if car in cars:
print(car.upper())
BMW’’’

‘’’ = 與 == ,= 是賦值,== 是判斷相等,區分大小寫,結果是布林值’’’
‘’‘car=‘Audi’
print(car==‘audi’)
False
print(car.lower()==‘audi’)
True’’’

‘’’ != 是判斷不相等,區分大小寫,結果是布林值’’’
‘’‘car=‘Audi’
print(car!=‘audi’)
True
print(car.lower()!=‘audi’)
False’’’

‘’’== != > < >= <= 常用來比較數字’’’
‘’'age=17

if age < 18:
print(‘你還未成年’)
你還未成年’’’
‘’‘and 和 or 檢查多條件 ‘’’
‘’‘True and True = True
True and False = False
False and False = False
False or False = False
False or True = True
True or True = True’’’
‘’'age = 20

if (age>=18) and (age<=22): #True and False = True
print(‘你還不能結婚,太小了’)

if (age>=18) or (age<=22): #True and False = True
print(‘你可以談戀愛了’)’’’

‘’‘檢查列表是否包含某值,返回布林值’’’
‘’'cars = [‘audi’,‘amg’,‘bmw’]

print(‘bmw’ in cars)
True
print(‘toyota’ in cars)
False’’’

‘’‘檢查列表不存在某值’’’
‘’'cars = [‘audi’,‘bmw’]

amg = ‘amg’
if amg not in cars:
print(amg.title()+’ is not exist’)
Amg is not exist’’’

‘’‘布林表示式記錄條件,跟蹤程式狀態’’’
game = True
study = False

‘’‘if-else語句,if條件未通過就執行else後面的語句’’’
‘’'age = 17

if age>18:
print(‘成年了’)
else:
print(‘未成年’)
未成年’’’

‘’‘if-elif-else語句 一次只執行一個程式碼段,if未通過執行elif,elif未通過執行else,elif可以有多個,else可以沒有’’’
‘’'age = 17

if age<15:
print(15)
elif age>18:
print(18)
else:
print(‘17’)
17’’’

‘’‘if-if-if語句 同時執行多個程式碼段’’’
‘’'cars = [‘amg’,‘bmw’,‘toyota’]

if ‘amg’ in cars:
print(‘amg’)
if ‘audi’ in cars:
print(‘audi’)
if ‘toyota’ in cars:
print(‘toyota’)
amg
toyota’’’

‘’‘if語句處理列表’’’
‘’'room = [‘gang’,‘liang’,‘dong’]

for name in room:
if name==‘liang’:
print(‘get out’)
else:
print(‘welcome’)
welcome
get out
welcome’’’

‘’‘確定列表不空’’’
‘’'cars = []

if cars:#不空
print(‘人滿了’)
else:
cars.append(‘liang’)
print(‘welcome’+str(cars))
welcome[‘liang’]’’’

‘’‘使用多個列表’’’
‘’'cars = [‘amg’,‘bmw’,‘toyota’,‘gang’]
room = [‘gang’,‘liang’,‘dong’]

for name in room:
if name in cars:
print(name + ’ have a car’)
else:
print(name+’ dont people have car’)
print(‘finish’)
gang have a car
liang dont people have car
dong dont people have car
finish’’’

相關文章