標籤:python 筆記 函數
from math import sqrt """import the sqrt function only""" e.g. sqrt(25)from math import * """import all functions from math module""" e.g. sqrt(25)import math #import math module,and use the function via math.* e.g. math.sqrt(25)
def distance_from_zero(a): if(type(a)==int or type(a)==float): #the type function return the type of the parameter,and when compare with any type,don‘t round it with quotation mark return abs(a)
#分割數組letters = [‘a‘, ‘b‘, ‘c‘, ‘d‘, ‘e‘] slice = letters[1:3] #slice will get letters[1] and letters[2] ,but no letters[3]print sliceprint letters#根據指定值擷取索引animals = ["aardvark", "badger", "duck", "emu", "fennec fox"]duck_index = animals.index("duck") #在指定索引位置插入值animals.insert(duck_index,"cobra")#將指定數組值刪除.removebackpack = [‘xylophone‘, ‘dagger‘, ‘tent‘, ‘bread loaf‘]backpack.remove(‘dagger‘)#list數組的for迴圈start_list = [5, 3, 1, 2, 4]square_list = []for number in start_list: #依次從start_list取值存入變數number中 square_list.append( number ** 2 ) #對取出的值平方後追加給square_listsquare_list.sort() #對square_list排序print square_list
menu = {} # 建立一個空字典menu[‘Chicken Alfredo‘] = 14.50 #添加索引值對menu[‘Tomato and Eggs‘] = 11menu[‘Frid Apple‘] = 9.8menu[‘Tu Dou‘] = 16.5del menu[‘Frid Apple‘] #刪除索引值對menu[‘Tu Dou‘]=10 #修改key對應的值print "There are " + str(len(menu)) + " items on the menu." #取字典長度len(menu)print menu#字典中的索引值對的資料類型可以多種多樣inventory = { ‘gold‘ : 500, ‘pouch‘ : [‘flint‘, ‘twine‘, ‘gemstone‘], # Assigned a new list to ‘pouch‘ key ‘backpack‘ : [‘xylophone‘,‘dagger‘, ‘bedroll‘,‘bread loaf‘]}# Adding a key ‘burlap bag‘ and assigning a list to itinventory[‘burlap bag‘] = [‘apple‘, ‘small ruby‘, ‘three-toed sloth‘]# Sorting the list found under the key ‘pouch‘inventory[‘pouch‘].sort() # 添加一個索引值對,該索引值對的值為listinventory[‘pocket‘] = [‘seashell‘,‘strange berry‘,‘lint‘]# 字典中list數組的引用跟數組本身的引用基本沒有區別inventory[‘backpack‘].sort()inventory[‘backpack‘].remove(‘dagger‘)inventory[‘gold‘] = inventory[‘gold‘] + 50#字典中的for迴圈,與list一致webster = {"Aardvark" : "A star of a popular children‘s cartoon show.", "Baa" : "The sound a goat makes.", "Carpet": "Goes on the floor.", "Dab": "A small amount."}# 輸出webster中所有key的值for web in webster: print webster[web] # 字典中for迴圈的應用執行個體prices = { "banana": 4, "apple": 2, "orange": 1.5, "pear": 3} stock = { "banana": 6, "apple": 0, "orange": 32, "pear": 15} for key in prices : print key print "price: %s"%(prices[key]) #注意輸出字串的拼接 print "stock: %s"%(stock[key])
本文出自 “DeathlessSun” 部落格,請務必保留此出處http://deathlesssun.blog.51cto.com/3343691/1658675
Python學習筆記之函數