Python控制结构

Python控制结构


1. Python控制结构简介

2. 定义函数

<1>. Python控制结构  

1.1 if
  1. print("#############if statement###############");
  2. x = int(input("Enter an integer :"));
  3. if x < 0 :
  4.     x = 0;
  5.     print("Negative changed to zero .");
  6. elif x == 0 :
  7.     print("Zero");
  8. elif x == 1 :
  9.     print("Single");
  10. else :
  11.     print("None");
复制代码
1.2 for
  1. ############################for statement
  2. print("#############for statement###############");
  3. a = ['cat', 'window',  'defenestrate'];
  4. for x in a :
  5.     print(x, len(x));
  6.    
  7. print("#############range function###############");
  8. for i in range(5) :
  9.     print(i);
  10. a = ['Mary', 'had', 'a', 'little', 'lamb'];
  11. for i in range(len(a)) :
  12.     print(i, a[i]);
复制代码
1.3 break and continue
  1. print("#############break and continue###############");
  2. for n in range(2, 10) :     # 2 - 9
  3.     for x in range(2, n):
  4.         if n % x == 0 :
  5.             print(n, 'equals', x,  '+', n // x);
  6.             break;
  7.         else :
  8.             print(n);
复制代码
1.4 pass
  1. # ########################pass action test ##############
  2. if False :
  3.     pass;   ''' do nothing '''
复制代码
<2>. 定义函数  2.1 定义函数基础
  1. # define the function
  2. def fib(n):
  3.     # print the Fibonacci series up to n.
  4.     a, b = 0, 1;
  5.     while  a < n :
  6.         print a;
  7.         a, b = b, a +b;
复制代码
2.2 函数默认参数
  1. '''  
  2.     default arguments
  3. '''
  4. def ask_ok(prompt, retries = 4, complaint = 'Yes or no, please') :
  5.     while True:
  6.         ok = raw_input(prompt);
  7.         if ok in ['y', 'Y', 'yes'] :
  8.             return True;
  9.         if ok in ['n', 'no', 'nop'] :
  10.             return False;
  11.         retries = retries - 1;
  12.         if retries < 0:
  13.             raise IOError('refusenik user');
  14.         print complaint;
复制代码
2.3 不定参数
  1. '''
  2.     Arbitrary arguments function
  3. '''
  4. def arbitraryArgsFunc(arg1, *args):
  5.    
  6.     # just print the arbitrary arguments
  7.     for i in range(0, len(args)):
  8.         print(args[i]);
  9.         
  10. arbitraryArgsFunc('arg1', 'arg2', 'arg3');
复制代码
2.4 Lambda表达式
  1. '''
  2.     lamba function, just like the function  template
  3. '''
  4. def make_incrementor(n):
  5.     return lambda x:x + n;
  6. f = f = make_incrementor(42);
  7. print(f(0));
复制代码

作者: 三里屯摇滚   发布时间: 2011-06-10

python 的语法真是优雅。

作者: coolesting   发布时间: 2011-06-13