極簡Python學習,【第6篇】函數 數據結構 封裝 異常處理

定義函數

def GetList(id):
    list=["aaa","bbb","ccc"]
    str =""
    for li in list:
        str+=li
    return  str

數據結構

a = [555, 133, 555, 1,356,77.7]
print(a.count(555), a.count(66.25), a.count('y'))
a.insert(2, 1000)
a.append(444)
print(a.index(555))
a.remove(555)
print(a)
del a[0]
print(a)

封裝模塊化

添加文件ObjList.py

在Main.py中調用GetList函數

錯誤和異常處理

while True:
    try:
        x = int(input("請輸入一個數字: "))
        break
    except ValueError:
        print("您輸入的不是數字,請再次嘗試輸入!")
import sys
for arg in sys.argv[1:]:
    try:
        f = open(arg, 'r')
    except IOError:
        print('cannot open', arg)
    else:
        print(arg, 'has', len(f.readlines()), 'lines')
        f.close()
try:
    abc() #未定義的函數
except AssertionError as error:
    print(error)
else:
    try:
        with open('abc.txt') as file:
            read_data = file.read()
    except FileNotFoundError as fnf_error:
        print(fnf_error)
finally:
    print('本行代碼一定會被執行。')

 

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章