Python學習筆記之基本文法

來源:互聯網
上載者:User

標籤: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)
  •     type函數的比較

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)
  •     list數組

#分割數組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‘)#刪除數組元素的三個函數#1.    n.pop(index)#n.pop(index) will remove the item at index from the list and return it to you:n = [1, 3, 5]n.pop(1)    # Returns 3 (the item at index 1)print n     # prints [1, 5]#2.    n.remove(item) will remove the actual item if it finds it:n.remove(1)  # Removes 1 from the list,NOT the item at index 1print n      # prints [3, 5]#3.    del(n[1]) is like .pop in that it will remove the item at the given index, but it won‘t return it:del(n[1])   # Doesn‘t return anythingprint n     # prints [1, 5]#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#數組組成的數組n = [[1, 2, 3], [4, 5, 6, 7, 8, 9]]#將數組lists中的所有數組的值取出形成一個新的數組def flatten(lists):    results=[]    for numbers in lists:        for number in numbers:            results.append(number)    return resultsprint flatten(n)
  •     字典

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])######################################################################################   小練習######################################################################################  lloyd = {                               #student lloyd    "name": "Lloyd",    "homework": [90.0, 97.0, 75.0, 92.0],    "quizzes": [88.0, 40.0, 94.0],    "tests": [75.0, 90.0]}alice = {                              #student alice    "name": "Alice",    "homework": [100.0, 92.0, 98.0, 100.0],    "quizzes": [82.0, 83.0, 91.0],    "tests": [89.0, 97.0]}tyler = {                              #student tyler    "name": "Tyler",    "homework": [0.0, 87.0, 75.0, 22.0],    "quizzes": [0.0, 75.0, 78.0],    "tests": [100.0, 100.0]}def average(numbers):               #get the average of a list of numbers    total = float(sum(numbers))    aver = total / len(numbers)    return aver    def get_average(student):          #get the average grade of any student    homework = average(student["homework"])    quizze = average(student["quizzes"])    test = average(student["tests"])    return 0.1 * homework + 0.3 * quizze + 0.6 * test    def get_letter_grade(score):       #get letter grade,like "A"/"B"/"C"    if(score>=90):        return "A"    elif(score>=80):        return "B"    elif(score>=70):        return "C"    elif(score>=60):        return "D"    else:        return "F"print get_average(lloyd)          #get the average grade of lloyd#get the average class grade of all students in the classdef get_class_average(students):    results=[]    for student in students :          results.append(get_average(student))    return average(results)class_average=get_class_average([lloyd,alice,tyler])print class_averageprint get_letter_grade(class_average)
  •     range()

#The range function has three different versions:#range(stop)#range(start, stop)#range(start, stop, step)#In all cases, the range() function returns a list of numbers from start up to (but not including) stop. Each item increases by step.#If omitted, start defaults to zero andstep defaults to one.range(6)         # => [0,1,2,3,4,5]range(1,6)       # => [1,2,3,4,5]range(1,6,3)     # => [1,4]


本文出自 “DeathlessSun” 部落格,請務必保留此出處http://deathlesssun.blog.51cto.com/3343691/1660234

Python學習筆記之基本文法

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.