定義函數
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('本行代碼一定會被執行。')