1. 程式人生 > >Python基礎例子(一)

Python基礎例子(一)

wan raise -- ase pri prime pam 如果 cci

編碼風格

  • 使用 4 空格縮進,而非 TAB

    在小縮進(可以嵌套更深)和大縮進(更易讀)之間,4空格是一個很好的折中。TAB 引發了一些混亂,最好棄用

  • 折行以確保其不會超過 79 個字符

    這有助於小顯示器用戶閱讀,也可以讓大顯示器能並排顯示幾個代碼文件

  • 使用空行分隔函數和類,以及函數中的大塊代碼

  • 可能的話,註釋獨占一行

  • 使用文檔字符串

  • 把空格放到操作符兩邊,以及逗號後面,但是括號裏側不加空格:a = f(1, 2) + g(3, 4)

  • 統一函數和類命名

    推薦類名用 駝峰命名, 函數和方法名用 小寫_和_下劃線。總是用 self 作為方法的第一個參數(關於類和方法的知識詳見 初識類 )

  • 不要使用花哨的編碼,如果你的代碼的目的是要在國際化環境。Python 的默認情況下,UTF-8,甚至普通的 ASCII 總是工作的最好

  • 同樣,也不要使用非 ASCII 字符的標識符,除非是不同語種的會閱讀或者維護代碼。

找素數

for n in range(2, 10):
    for x in range(2, n):
        if n % x == 0:
            print(n, equals, x, *, n//x)
            break
    else:
        print(n, is a prime number)

        
2 is a prime number 3 is a prime number 4 equals 2 * 2 5 is a prime number 6 equals 2 * 3 7 is a prime number 8 equals 2 * 4 9 equals 3 * 3

找奇偶

for num in range(2, 10):
    if num % 2 == 0:
        print(Found an even number, num)
        continue
    print(Found a number, num)

    
Found an even number 
2 Found a number 3 Found an even number 4 Found a number 5 Found an even number 6 Found a number 7 Found an even number 8 Found a number 9

一個能打印斐波那契的函數

>>> def fib(n):
    """Print a Fibonacci series up to n."""
    a, b = 0, 1
    while a < n:
        print(a, end =  )
        a, b = b, a+b
    print()

    
>>> fib(500)
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 

帶默認參數的函數

>>> def ask_ok(prompt, retries=4, complaint=Yes or no,Please!):
    while True:
        ok = input(prompt)
        if ok in (y, ye, yes):
            return True
        if ok in (n, no, nop, nope):
            return False
        retries = retries - 1
        if retries < 0:
            raise OSError(uncooperative user)
        print(complaint)

        
>>> ask_ok(Do you really want to quit?)
Do you really want to quit?what?
Yes or no,Please!
Do you really want to quit?yes
True

默認值只被賦值一次,當默認值是可變對象時會有所不同,比如列表、字典或者大多數類的實例。

例如,下面的函數在後續調用過程中會累積(前面)傳給它的參數

>>> def f(a, L=[]):
    L.append(a)
    return L

>>> print(f(1))
[1]
>>> print(f(2))
[1, 2]
>>> print(f(3))
[1, 2, 3]
>>> 

關鍵字函數

>>> def parrot(voltage, state=a stiff, action=voom, type=Norwegian Blue):
    print("-- This parrot wouldn‘t", action, end= )
    print("if you put", voltage, "volts through it.")
    print("-- Lovely plumage, the", type)
    print("-- It‘s", state, "!")

    
>>> parrot(1000)
-- This parrot wouldnt voom if you put 1000 volts through it.
-- Lovely plumage, the Norwegian Blue
-- Its a stiff !
>>> parrot(a thousand, state=pushing up the daisies)
-- This parrot wouldnt voom if you put a thousand volts through it.
-- Lovely plumage, the Norwegian Blue
-- Its pushing up the daisies !

元組、字典的作為參數的函數

>>> def cheeseshop(kind, *arguments, **keywords):
    print("-- Do you have any", kind, "?")
    print("-- I‘m sorry, we‘re all out of", kind)
    for arg in arguments:
        print(arg)
    print("-" * 40)
    keys = sorted(keywords.keys())
    for kw in keys:
        print(kw, ":", keywords[kw])

        
>>> cheeseshop("Limburger", "It‘s very runny, sir.",
           "It‘s really very, VERY runny, sir.",
           shopkeeper="Michael Palin",
           client="John Cleese",
           sketch="Cheese Shop Sketch")
-- Do you have any Limburger ?
-- Im sorry, were all out of Limburger
Its very runny, sir.
Its really very, VERY runny, sir.
----------------------------------------
client : John Cleese
shopkeeper : Michael Palin
sketch : Cheese Shop Sketch

函數註解

對於參數的註解出現在緊隨參數名之後的冒號之後

對於返回值,它們編寫於緊跟在參數列表之後的一個 -> 之後.

>>> def func(a:‘spam‘,b:(1,10),c:float)->int:  
	return a+b+c

>>> func.__annotations__
{‘a‘: ‘spam‘, ‘b‘: (1, 10), ‘c‘: <class ‘float‘>, ‘return‘: <class ‘int‘>}

Python基礎例子(一)