python学习-函数-实例1

三个函数

def power(x,y):
    'x的y次幂'
    a = x ** y
    return a
        
def gcd(x,y):
    'x,y的最大公约数;欧几里得算法'
    a = max(x,y)
    b = min(x,y)
    while 1:
        c = a%b
        if c == 0:
            break
        else:
            a = b
            b = c
            continue
    return b

def dec2bin(dec):
    '十进制转二进制;除2取余法'
    a = []
    while 1:
        b = dec//2
        c = dec%2
        a.insert(0,c)
        if b == 0:
            break
        else:
            dec = b
            continue
    d = [0,'b']
    d.extend(a)
    r = ''
    for i in d:
        e = str(i)
        r = r+e
    return r

调用结果

>>> power(3,3)
27
>>> gcd(123456,7890)
6
>>> dec2bin(10)
'0b1010'
>>> bin(10)
'0b1010'
>>> 

你可能感兴趣的:(python学习-函数-实例1)