2014年12月9日 星期二

python 常用方法,函數,筆記

1:os.path.isfile  確認檔案是否存在

2:
import os
filename = os.environ.get(''PYTHONSTARTUP)
if filename and os.path.isfile(filename):
    exec(open(filename).read());

3:
print(b,end=",")
1,1,2,3,5,8,13,21,34,

4:
x=int(input("\nplease enter a number:"))
if x < 10:
   print("x < 10")
elif x < 20:
   print("x < 20")
else:
   print("haha")

5:print(n,'equals',x,'x',n//x)
4 equals 2 * 2


6:
def fib(n):
    a,b = 0 ,1
    while b < n:  
       print("haha=",b)
       a,b = b,a+b
   
fib(100)

7:
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?")


8:
def printdoc():
    """
    Doc start
   
    Doc medion
   
    Doc botton
    """
    pass

print(printdoc.__doc__)

9: 除法不要小數點
5 // 2
要小數點
5 / 2

階乘
5 ** 2

10:
def max(m, n):
    return m if m > n else n

print(max(10, 3))  # 顯示 10

類似c 三位元運算子,  val  = x ? y : z ;

11:列表推導
squares = [x**2 for x in range(10)]

沒有留言:

張貼留言