1. Python Control Structure
2. define functions
<1>. Python Control Structure 1.1 ifprint ("############# if statement ###############"); X = int (input ("enter an integer:"); If x <0: x = 0; print ("negative changed to zero. "); Elif x = 0: Print (" zero "); Elif x = 1: Print (" single "); else:
Print ("NONE ");
1.2 For ########################## for statementprint ("###### ####### for statement ###############"); A = ['cat', 'window', 'deletestrate']; for X in A: Print (x, Len (x )); print ("############ range Function ###############"); for I in range (5): Print (I); A = ['Mary ', 'had', 'A', 'Little', 'lamb']; for I in range (LEN ()):
Print (I, a [I]);
1.3 break and continueprint ("############# break and continue ###############"); for N in range (2, 10): #2-9 for X in range (2, n): If n % x = 0: Print (n, 'equal ', x, '+', N // X); break; else: Print (N ); 1.4 pass ######################### pass action test ########## #### if false: pass; ''' do nothing '''
<2>. Define a function 2.1 define function basics # define the functiondef fib (n): # print the Fibonacci series up to n. a, B = 0, 1; while a <n: print;
A, B = B, A + B;
2.2 default function parameter '''default arguments ''' def ask_ OK (prompt, retries = 4, complaint = 'yes or no, please'): While true: OK = raw_input (prompt); If OK in ['y', 'y', 'yes']: Return true; If OK in ['n', 'No ', 'nop']: Return false; retries = retries-1; if retries <0: Raise ioerror ('refusenik user ');
Print complaint;
2.3 The parameter '''arbitrary arguments function''' def arbitraryargsfunc (arg1, * ARGs): # Just print the arbitrary arguments for I in range (0, Len (ARGs )): print (ARGs [I]);
Arbitraryargsfunc ('arg1', 'arg2', 'arg3 ');
2.4 lambda expressions '''lamba function, just like the function template ''' def make_incrementor (n): Return Lambda X: x + N; F = f = make_incrementor (42 );
Print (f (0 ));