1. 程式人生 > >ex19-20 函數、變量和文件

ex19-20 函數、變量和文件

我只 let scrip rom current ann 偏移 fun ren

ex19

函數中的全局變量和腳本中的變量沒有聯系,函數中的變量可以通過多種方式賦予。

 1 #-*- coding: UTF-8 -*- 
 2 def cheese_and_crackers(cheese_count,boxes_of_crackers):
 3   print "You have %d cheese!" % cheese_count
 4   print "You have %d boxes of crackers!" % boxes_of_crackers
 5   print "Man that‘s enough for a party!"
 6   print "Get a blanket.\n
" 7 #創建函數:設置兩個參數;四個包含了參數的print。 8 9 10 print "We can just give the function number directly:" 11 cheese_and_crackers(20,30) #直接對函數中的參數賦值 12 13 print "OR,we can use variables from our script." 14 amount_of_cheese = 10 15 amount_of_crackere = 5 16 17 cheese_and_crackers(amount_of_cheese,amount_of_crackere)#
通過腳本中的變量來對函數的參數賦值 18 19 print "We can even do math inside too." 20 cheese_and_crackers (10+20,5+6)#在函數內進行運算 21 22 23 print "And we can combine the two,variable and the math." 24 cheese_and_crackers(amount_of_cheese+10,amount_of_crackere+1000)#在函數內進行運算,並通過腳本中的變量進行 25 #發現一個特點,創建的這個函數,不僅僅是包括參數,還包括下邊二級代碼的那一系列指令。

附加練習:自己編寫一個函數,並至少用10種方式運行(我只用了3種 ==)

 1 #-*- coding: UTF-8 -*- 
 2 def shopping_list (what_I_want,price):#老是會忘記冒號,要經常提醒自己。
 3    print "So I wanna %s And its price is %d RMB"% (what_I_want,price)#前面設置兩種不同的格式化字符,後邊也可以給放到一個括號裏邊)
 4    print "Fine,let us just take it."
 5    
 6 print "Now I gonna go shopping." 
 7 shopping_list ("Juice" ,10)
 8 
 9 print "Now I want two kinds of beer."
10 shopping_list("IPA"+"\tLager",10+15)#如果想要\t起到空格的作用,那麽就需要在前面設置為%s
11 
12 print "OK i also wanna something for dinner."
13 dish = "pork"+"&eggs"
14 the_price = 30+10#要非常註意,腳本中的變量和函數中的全局變量不要設置成相同
15 shopping_list(dish,the_price)
16 
17 print "HAHA man you look just like a idiot."

ex20

 1 #-*- coding: UTF-8 -*- 
 2 from sys import argv
 3 
 4 script,input_file = argv
 5 
 6 def print_all(f):#創建函數,讀取並打印文件內容
 7  print f.read()#後邊如果不加(),就沒法讀,或者讀了也沒法打印
 8 
 9 def rewind (f):#創建函數,把文件指針設置到從頭開始
10  print f.seek(0)
11  
12 def print_a_line(line_count,f):#創建函數,按照行來讀取並打印文件
13  print line_count,f.readline()
14  
15 current_file = open(input_file)#打開文件
16 
17 print"First lets read the whole file.\n"
18 
19 print_all (current_file) #一開始還疑惑是否可以直接用 Input_file ,後來發現自己傻了,肯定要先打開啊~~
20 
21 print "Now let‘s rewind,kind of like a tape."#不是很明白這裏rewind的意義,難道在進行上一步之後指針到了最後了?
22 
23 rewind(current_file)
24 
25 print "Let‘s print three lines."
26 #逐行讀取並打印
27 current_line = 1
28 print_a_line(current_line,current_file)
29 
30 current_line = current_line + 1 #也可以寫成current_line += 1
31 print_a_line(current_line,current_file)
32 
33 current_line = current_line + 1
34 print_a_line(current_line,current_file)
35 
36 ‘‘‘
37 file.seek()方法標準格式是:seek(offset,[whence=0])offset:相對於whence的偏移量,字節數,可以為負數,
38 whence省略時,默認從文件開頭算起
39 whence:給offset參數的偏移參考,表示要從哪個位置開始偏移;0代表從文件開頭開始算起,1代表從當前位置開始算起,2代表從文件末尾算起
40 ‘‘‘

ex19-20 函數、變量和文件