Iv. Process Control
在这块,Python与其它大多数语言有个非常不同的地方,Python语言使用缩进块来表示程序逻辑(其它大多数语言使用大括号等)。例如:
If age < 21:
print("你不能买酒。")print("不过你能买口香糖。")
Print ("This sentence is outside of the IF statement block.) ”)
这个代码相当于c语言的:
if (age < 21)
{
print("你不能买酒。")print("不过你能买口香糖。")
}
Print ("This sentence is outside of the IF statement block.) ”)
可以看到,Python语言利用缩进表示语句块的开始和退出(Off-side规则),而非使用花括号或者某种关键字。增加缩进表示语句块的开始(注意前面有个:号),而减少缩进则表示语句块的退出。根据PEP的规定,必须使用4个空格来表示每级缩进(不清楚4个空格的规定如何,在实际编写中可以自定义空格数,但是要满足每级缩进间空格数相等)。使用Tab字符和其它数目的空格虽然都可以编译通过,但不符合编码规范。 为了使我们自己编写的程序能很好的兼容别人的程序,我们最好还是按规范来,用四个空格来缩减(注意,要么都是空格,要是么都制表符,千万别混用)。
1, If-else
If-else用来判断一些条件,以执行满足某种条件的代码。
[Python] View plain copy
View code slices to my Code slice
################################ ######## procedure control ##### ## if else if expression: # bool type and do not forget the colon statement(s) # use four space key if expression: statement(s) # error!!!! should use four space key if 1<2: print ‘ok, ‘ # use four space key print ‘yeah‘ # use the same number of space key if True: # true should be big letter True print ‘true‘ def fun(): return 1 if fun(): print ‘ok‘ else: print ‘no‘ con = int(raw_input(‘please input a number:‘)) if con < 2: print ‘small‘ elif con > 3: print ‘big‘ else: print ‘middle‘ if 1 < 2: if 2 < 3: print ‘yeah‘ else: print ‘no‘ print ‘out‘ else: print ‘bad‘ if 1<2 and 2<3 or 2 < 4 not 0: # and, or, not print ‘yeah‘
2. For
for的作用是循环执行某段代码。还可以用来遍历我们上面所提到的序列类型的变量。
[Python] View plain copy
View code slices to my Code slice
################################ ######## Procedure Control ##### # # for-Iterating_val in sequence:statements (s) # sequence type can is string, tuple or list for I in ' ABCD ': Print I for i in [1, 2, 3, 4]: print I # R Ange (Start, end, step), if not set to step, default is 1, # If does set start, default is 0, should being noted that it is [STA RT, end), not [start, end] Range (5) # [0, 1, 2, 3, 4] range (1, 5) # [1, 2, 3, 4] range (1,, 2) # [1, 3, 5, 7, 9] for I in range (1, 1): Print I # ergodic for basis sequence fruits = [' apple ', ' banana ', ' mango '] for fruit in R Ange (len (fruits)): print ' current fruit: ', Fruits[fruit] # ergodic for dictionary dic = {1:111, 2:222, 5:555} For x in Dic:print x, ': ', Dic[x] Dic.items () # return [(1, 111), (2, 222), (5, 555)] for Key,value in Dic.items (): # because we can:a,b=[1,2] print key, ': ', Value else:print ' ending ' ################################ Import Time # We also CAn use:break, continue-to-control process for x in range (1, one): Print x Time.sleep (1) # sleep 1s if x = = 3:pass # do nothing if x = = 2:continue if x = = 6:break if x = = 7: Exit () # exit the whole program print ' # ' *50
3. While
while的用途也是循环。它首先检查在它后边的循环条件,若条件表达式为真,它就执行冒号后面的语句块,然后再次测试循环条件,直至为假。冒号后面的缩近语句块为循环体。
[Python] View plain copy
View code slices to my Code slice
################################ ######## procedure control ##### ## while while expression: statement(s) while True: print ‘hello‘ x = raw_input(‘please input something, q for quit:‘) if x == ‘q‘: break else: print ‘ending‘
4. Switch
其实Python并没有提供switch结构,但我们可以通过字典和函数轻松的进行构造。例如:
[Python] View plain copy
View code slices to my Code slice
############################# ## switch #### ## this structure do not support by python ## but we can implement it by using dictionary and function ## cal.py ## #!/usr/local/python from __future__ import division # if used this, 5/2=2.5, 6/2=3.0 def add(x, y): return x + y def sub(x, y): return x - y def mul(x, y): return x * y def div(x, y): return x / y operator = {"+": add, "-": sub, "*": mul, "/": div} operator["+"](1, 2) # the same as add(1, 2) operator["%"](1, 2) # error, not have key "%", but the below will not operator.get("+")(1, 2) # the same as add(1, 2) def cal(x, o, y): print operator.get(o)(x, y) cal(2, "+", 3) # this method will effect than if-else
Five, function
1. Custom Functions
在Python中,使用def语句来创建函数:
[Python] View plain copy
View code slices to my Code slice
################################ ######## function ##### def functionname (parameters): # No parameters is OK bodyo Ffunction def add (A, B): Return A+b # If we do not use a return, any defined function would return default None a = + b = sum = Add (A, b) ##### function.py ##### #!/usr/bin/python #coding: UTF8 # support Chinese def add (a = 1 , B = 2): # Default parameters return A+b # can return any type of data # The followings is all OK Add () Add (2) Add (y = 1) Add (3, 4) ###### the global and local value ##### # # Global value:defined outside any function, and can be Used # in-anywhere, even in functions, this should be noted # # local value:defined inside a function, an D can only be used # in its own function # # The local value would cover the global if they have the same NA Me val = # global Value def fun (): Print Val # Here's access the Val = + Print Val # Here's access the val = too def fun(): A = # local value print a print a # here can not access the A = + def fun (): Global a = # D Eclare as a global value print a print a # here can not access the A = +, because fun () not being called yet fun () Print a # here can access the A = ############################ # # Other types of Parameters def fun (x): Print X # The follows is all OK Fun () # int fun (' Hello ') # string Fun ((' X ', 2, 3)) # Tuple Fun ([1, 2, 3]) # list Fu N ({1:1, 2:2}) # dictionary # tuple def fun (x, y): print "%s:%s"% (x, y) #%s stands-string fun (' Zou ', ' XI Aoyi ') Tu = (' Zou ', ' Xiaoyi ') Fun (*tu) # can transfer a tuple parameter like this # # dictionary def fun (name = "Name") , age = 0): print ' name:%s '% name print ' Age: '% age dic = {name: ' Xiaoyi ', age:25} # The keys of Dictionar Y should be same as fun (**dic) # can transfer dictionary parameter like this fun (age = +, name = ' Xiaoyi ') # the result is the same # # THe advantage of dictionary is can specify value name ############################# # # redundancy Parameters # # # # The Tuple def fun (x, *args): # The extra parameters would stored in args as tuple type print x print args # the F Ollows is OK fun (ten, a) # x = ten, args = (k, x) # # The Dictionary def Fun (**args): # The Extra para Meters'll stored in args as dictionary type print x print args # The follows is OK fun (x = ten, Y = x, z = +) # × = ten, args = {' Y ': +, ' Z ': $} # Mix of tuples and dictionary def Fun (x, *args, **kwargs): Print x print args Print Kwargs fun (1, 2, 3, 4, y = ten, z = +) # x = 1, args = (2, 3, 4), Kwargs = {' Y ': ten, ' Z ': 12 }
2. Lambda function
Lambda函数用来定义一个单行的函数,其便利在于:
[Python] View plain copy
View code slices to my Code slice
############################# ## lambda function #### ## define a fast single line function fun = lambda x,y : x*y # fun is a object of function class fun(2, 3) # like def fun(x, y): return x*y ## recursion # 5=5*4*3*2*1, n! def recursion(n): if n > 0: return n * recursion(n-1) ## wrong def mul(x, y): return x * y numList = range(1, 5) reduce(mul, numList) # 5! = 120 reduce(lambda x,y : x*y, numList) # 5! = 120, the advantage of lambda function avoid defining a function ### list expression numList = [1, 2, 6, 7] filter(lambda x : x % 2 == 0, numList) print [x for x in numList if x % 2 == 0] # the same as above map(lambda x : x * 2 + 10, numList) print [x * 2 + 10 for x in numList] # the same as above
3. Python built-in functions
Python内置了很多函数,他们都是一个个的.py文件,在python的安装目录可以找到。弄清它有那些函数,对我们的高效编程非常有用。这样就可以避免重复的劳动了。下面也只是列出一些常用的:
[Python] View plain copy
View code slices to my Code slice
################################### # # built-in function of Python # # # # # If do not ' how to ' use, ' use ' Help () ABS, Max, Min, Len, Divmod, POW, round, callable, Isinstance, CMP, range, xrange, type, id, int () list (), tuple (), Hex (), OC T (), Chr (), Ord (), Long () callable # Test A function whether can is called or not, if can, return true # or test a funct Ion is exit or isn't isinstance # test Type numlist = [1, 2] if type (numlist) = = Type ([]): print "It is a list" if Isinstance (Numlist, list): # The same as above, return true print ' It is a list ' for I in range (1, 10001) # would CRE Ate a 10000 list, and cost memory for I in xrange (1, 10001) # does not create such a list, no memory was cost # # some basic Functions about string str = ' Hello World ' str.capitalize () # ' Hello World ', first letter transfer to big Str.replace (" Hello "," good ") # ' good world ' IP = ' 192.168.1.123 ' ip.split ('. ') # return [' 192 ', ' 168 ', ' 1 ', ' 123 '] help (Str.split) Import string str = ' HeLlo World ' string.replace (str, "Hello", "good") # ' Good World ' # # Some basic functions about sequence len, Max, Min # Filter (function or none, Sequence) def fun (x): if x > 5:return True numlist = [1, 2, 6, 7] filter (fun , numlist) # get [6, 7], if fun return True, retain the element, otherwise delete it filter (lambda x:x% 2 = = 0, Numlis T) # Zip () name = ["Me", "you"] = ["123", "234"] Zip (name, age, tel) # return a list: [(' Me ', 25, ' 123 '), (' You ', ' + ', ' 234 ')] # map (None, name, age, tel) # also return a list: [(' Me ', ' + ', ' 123 '), (' You ', 26, ' 234 ')] test = ["Hello1", "Hello2", "Hello3"] Zip (name, age, Tel, test) # return [(' Me ', ' + ', ' 123 ', ' Hello1 '), (' You ', 26, ' 234 ', ' Hello2 ')] Map (None, name, age, Tel, test) # return [(' Me ', ' + ', ' 123 ', ' Hello1 '), (' You ', ' + ', ' 234 ', ' Hello2 '), (No NE, none, none, ' Hello3 ')] a = [1, 3, 5] b = [2, 4, 6] def mul (x, y): Return x*y map (Mul, A, b) # return [2, 12, # Reduce () reduce (Lambda x, Y:x+y, [1, 2, 3, 4, 5]) # Return ((((1+2) +3) +4) +5)
Guangdong Ocean University electronic 1151-hole Yanfei Python language programming third week