Python控制結構

來源:互聯網
上載者:User

1. Python控制結構簡介

2. 定義函數 

<1>. Python控制結構  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',  'defenestrate'];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(a)) :

    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, 'equals', x,  '+', n // x);            break;        else :            print(n);1.4 pass# ########################pass action test ##############if False :    pass;   ''' do nothing ''' <2>. 定義函數  2.1 定義函數基礎# define the functiondef fib(n):    # print the Fibonacci series up to n.    a, b = 0, 1;    while  a < n :        print a;

        a, b = b, a +b; 

2.2 函數預設參數 '''      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 不定參數'''    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運算式'''    lamba function, just like the function  template'''def make_incrementor(n):    return lambda x:x + n;f = f = make_incrementor(42);

print(f(0)); 

相關文章

聯繫我們

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