python學習7——函數

來源:互聯網
上載者:User

標籤:fun   分享   input   inf   mes   sub   back   作用   use   

 

1、函數。

def profit(volume, price,cost):    print("We sell %d ice cream a day." % volume)    print("You can buy an ice cream at the price of %d dollars" % price)    print("Make an ice cream will cost us %d dollars." % cost)    print("Then our daily profit can be %d dollars." %((price-cost)*volume))print("We can just give the function numbers directly:" )profit(500,20,10)print("Or we can use variables from our script:")volume = 200price  =10cost  = 3profit(volume,price,cost)

輸出結果:

 2、函數和檔案。

from sys import argvscript, input_file = argvdef print_all(f):  print(f.read())def rewind(f):  f.seek(0)def print_a_line(line_count,f):  print(line_count,f.readline())current_file = open(input_file)print("First let‘s print the whole file:\n")print_all(current_file)print("Now let‘s rewind, kind of like a tape).")rewind(current_file)print("Let‘s print three lines:")current_line = 1print_a_line(current_line,current_file)current_line = current_line+1print_a_line(current_line,current_file)current_line = current_line+1print_a_line(current_line,current_file)

輸出結果:

為了知道+=的作用,我將代碼修改為:

from sys import argvscript, input_file = argvdef print_all(f):  print(f.read())def rewind(f):  f.seek(2)def print_a_line(line_count,f):  print(line_count,f.readline())current_file = open(input_file)print("First let‘s print the whole file:\n")print_all(current_file)print("Now let‘s rewind, kind of like a tape.")rewind(current_file)print("Let‘s print three lines:")current_line = 1print_a_line(current_line,current_file)current_line+= current_line+1print_a_line(current_line,current_file)

輸出結果:

可以看到,第二行的內容沒有被列印出來。

結論:

a+=b 即為 a=a+b

3、return

def add(a,b): print("ADDING %d + %d" % (a,b)) return a+bdef subtract(a,b): print("SUBTRACTING %d-%d" % (a,b)) return (a-b)def multiply(a,b): print ("MULTIPLYING %d * %d"%(a,b)) return (a*b)def divide(a,b): print("DIVIDING %d / %d" %(a,b)) return (a/b)print("Let‘s do some math with just functions!")age = add(30,5)height = subtract(70,4)weight=multiply(90,2)iq = divide(150,2)print("Age: %d, Height: %d, Weight: %d, IQ: %d" %(age,height,weight,iq))print("Here is a puzzle.")what = add(age, subtract(height,multiply(weight, divide(iq,2))))print("That becomes:",what,"\n Can you do it by hand?")

輸出結果:

 

python學習7——函數

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.