python笔记——函数练习

1、输入字符串,分别字符串中含有数字、字母、空格和其它字符个数。

def findstr(*param):
    chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
    nums = '0123456789'
    space = ' '
    count_char = 0
    count_num = 0
    count_sp = 0
    count_sym = 0
    for i in x:
        if i in chars:
            count_char += 1
        elif i in nums:
            count_num += 1
        elif i == space:
            count_sp += 1
        else:
            count_sym +=1
    print("有英文字母%d个,数字%d个,空格%d个,其它字符%d个"%(count_char, count_num, count_sp, count_sym))            
x = str(input("请输入字符串"))
findstr(x)

2、统计一个长度为2的子字符串在另一个字符串中出现的次数:

def findstr(x,y):
    result = []
    length = len(x)
    count = 0
    for i in range(length-1):
        result.append(x[i:i+2])
    for i in result:
        if y == i:
            count +=1
    return count
x = str(input("字符串"))
y = str(input("子字符串"))
print(findstr(x,y))

3、定义一个函数,求两个整数的最大公约数:

def gcd(x, y):
    result = 0
    result1 = []
    if x>=y:
        result = y
    else:
        result = x
    for i in range(1,result+1):
        if x%i ==0 and y%i ==0:
            result1.append(i)
    return max(result1)
print(gcd(12,8))

4、自己定义一个min()函数,来查看它的实现原理:

def min(x):
    result = x[0]
    for i in x:
        if result <=i:
            continue
        else:
            result = i
    return result
min([1,2,3])

5、定义一个sum()函数,如果不是参数不是整数或浮点数自动略过

def sum(x):
    result = 0
    for i in x:
        if (type(i) == int) or (type(i) == float):
            result += i
        else:
            continue
    return result
a = [1,2,3]
print(sum(a))

你可能感兴趣的:(python,python入门总结)