Python初学者自励——函数和代码的复用

第五章函数和代码的复用
打招呼函数
请用程序实现
用函数给某个人打招呼。

函数定义
def say_hello (name):
pass
参数说明
name是一个字符串,表示名字。

返回值说明
该函数没有返回值,调用该函数会输出一段话:你好,xxx,认识你很高兴!

"""
练习:打招呼函数
要求:
1. 定义函数 say_hello
2. 有 1 个参数 name 表示要给谁打招呼
3. 实现函数功能,即在控制台打印:`你好,,认识你很高兴!`(注:name 是函数的参数)
"""
def say_hello(name):
    n=name
    print("你好,{},认识你很高兴!".format(n))
name=input()
say_hello(name)

=====================================
能否组成三角形
判断三条线段能否构成一个三角形,需要满足两条规则:

三角形的三条边长必须大于零。
任意两边之和必须大于第三边。
请用程序实现
用函数判断三个数字能否构成三角形,并将判断结果返回。

"""
编写 is_triangle 函数,此函数有 3 个参数,分别为3个数字,
判断这3个数字所代表的边长能否组成一个三角形
"""
def is_triangle(a, b, c):
    if a>0 and b>0 and c>0:#每边大于零
        if (a+b) >c and (a+c) >b and (b+c) >a:#两边之和大于第三边
            return 1
        else:
            return 0
    else:
        return -1

x =0
y =1
z =1
s=is_triangle(x,y,z)
print(s)

=====================================
转换秒为时间
1 天有 86400 秒,那么 100000 秒相当于多长时间呢?

请用程序实现
用函数实现,将一个指定的秒数转换为[天, 时, 分, 秒]的数据格式,并将其返回。

# 定义一个 convert_from_seconds 函数, 参数 seconds, 返回表示时间的列表
def convert_from_seconds (seconds):
    #day,h,m,s
    int(seconds)
    day=seconds//86400
    h=(seconds-day*86400)//3600
    m=(seconds-day*86400-h*3600)//60
    s=(seconds-day*86400-h*3600-m*60)
    return [day,h,m,s]

print(convert_from_seconds (610))

===================================
最大公约数
请用程序实现
用函数计算两个整数的最大公约数,并将计算结果返回。

# 定义并实现函数 common_divisor
def common_divisor(num1, num2):
    if num1>num2:
        for i in range(2,num2+1):
            if num1%i==0 and num2%i==0:
                result=i
    if num1<num2:
        for i in range(2,num1+1):
            if num1%i==0 and num2%i==0:
                result=i
    return result

# 调用函数
result = common_divisor(24, 16)
print(result)

=====================================
简单计算器实现
请用程序实现
用函数实现 加、减、乘、除 的运算。

# 定义加法函数 addition
def addition (num1, num2):
    return num1+num2

# 定义减法函数 subtraction
def subtraction (num1, num2):
    return num1-num2

# 定义乘法函数 multiplication
def multiplication (num1, num2):
    return num1*num2

# 定义除法函数 division
def division (num1, num2):
    return num1/num2

=====================================
杨辉三角
杨辉三角,又称贾宪三角形、帕斯卡三角形,是二项式系数在三角形中的一种几何排列。以下是杨辉三角的前十行:

              1
            1   1
          1   2   1
        1   3   3   1
      1   4   6   4   1
    1   5   10  10  5   1
  1   6   15  20  15  6   1
1   7   21  35  35  21  7   1

1 8 28 56 70 56 28 8 1
1 9 36 84 126 126 84 36 9 1
由上可以看出:

每行端点与结尾的数为 1
每个数等于它上方两数之和
每行数字左右对称,且由 1 开始逐渐变大
第 n 行的数字有 n 项
请用程序实现
用函数实现,返回一个指定行数的杨辉三角数列。

# 定义函数 pascal_triangle 接受参数 num,并返回杨辉三角第 num 行
# 定义函数 pascal_triangle 接受参数 num,并返回杨辉三角第 num 行
def pascal_triangle(num):
    l1 = [1]
    l2 = []
    n = 0
    while n < num:
       # l2.append(l1)
        l2 = l1
        l1 = [sum(t) for t in zip([0]+l1, l1+[0])]
        n += 1
    return l2
print(pascal_triangle(3))

====================================
斐波那契数列计算
形如1,1,2,3,5,8…的数列,被称之为斐波那契数列。这个数列的特点是从第三个数字开始,每个数字都等于前两个数字之和。

请用程序实现
用函数实现,计算斐波那契数列某项的值,并将计算结果返回。

# 定义一个 fbi 函数,参数 num,返回斐波那契数列第 num 项的值。
def fbi(num):
    rList=[1,1,""]
    for i in range(2,num):
        rList[i]=rList[i-1]+rList[i-2]
        rList.append(rList[i])
    return rList[num]
print(fbi(4))

=====================================
汉诺塔实践
请用程序实现
用函数实现汉诺塔的移动步骤拆解。

# 请在...补充一行或多行代码
count = 0

def hanoi (n, src, dst, mid):
    global count
    if n == 1:
        print("{}: {}->{}".format(1, src, dst))
        count += 1
    else:
        

hanoi(3, "A", "C", "B")
print(count)

=====================================
合法的用户名
有一些网站注册用户时,会对用户名长度进行限制,比如用户名的长度必须在6(含)~18(含)位之间。

请用程序实现
用函数实现对用户名的合法性进行检查。

"""
实现 check_username 函数,检查 username 是否有效
username 长度在 6-18 位之间,返回 True,否则返回 False
"""
def check_username(username):
    if 6<=len(str(username))<=18:
        return True
    else:
        return False
user=input
print(check_username(user))

密码的强度
密码是账户的重要安全保障,涉及到安全问题,太简单的密码容易被猜到或破解。

请用程序实现
用函数实现一个校验密码强度的函数,用于提醒用户在注册时,密码是否足够安全。

以下为密码强度校验规则:

密码长度在 6 位及以上,强度 +1,在 8 位及以上,强度 +2,12 位及以上,强度 +4
有大写字母,强度 +2
除字母外,还包含数字,强度 +2
有除字母、数字以外字符强度 +2

def password_strength(pwd):
    intensity=0
    if len(pwd)>=12:
        intensity+=4
    elif 8<=len(pwd)<12:
        intensity+=2
    elif 6<=len(pwd)<8:
        intensity+=1
    pwdlist=list(pwd)
    for i in range(len(pwd)):
        if 'A'<=pwdlist[i]<='Z':
            intensity+=2
            break
    for i in range(len(pwd)):
        if 'A'<=pwdlist[i]<='Z' or 'a'<=pwdlist[i]<='z':
            for j in range(len(pwd)):
                if '0'<=pwdlist[j]<='9':
                    intensity+=2
                    break
        break
    for i in range(len(pwd)):
        if ('null'<=pwdlist[i]<'0') or ('9'<pwdlist[i]<='@') or ('Z'<pwdlist[i]<='`') or ('z'<pwdlist[i]<='~'):
            intensity+=2
            break
    return intensity
pwd1=str(input())
print(password_strength(pwd1))

====================================
藏头诗
古人经常使用藏头诗,隐晦的表达自己的想说的话,既有诗意,又能传递信息,比如下面这两首诗:

芦花丛中一扁舟,
俊杰俄从此地游。
义士若能知此理,
反躬难逃可无忧。

我画蓝江水,
爱晚亭上枫。
秋月溶溶照,
香烟袅袅绕。
请用程序实现
用函数实现,将藏头诗中隐含的意思找出来。

poem1 = [
    "芦花丛中一扁舟",
    "俊杰俄从此地游",
    "义士若能知此理",
    "反躬难逃可无忧"
]

poem2 = [
    "我画蓝江水",
    "爱晚亭上枫",
    "秋月溶溶照",
    "香烟袅袅绕"
]


def acrostic(poem):
    newstr=[]
    for i in range(len(poem)):
        str1=poem[i]
        rstr=list(str1)
        newstr.append(rstr[0])
        str1=""
    newstr1=''.join(newstr)
    return newstr1


print(acrostic(poem1))
print(acrostic(poem2))

=====================================
统计字符出现次数
请用程序实现
用函数实现,统计字符串中指定字符出现的次数。

"""
统计字符串 string 中出现字符 char 的次数,并返回;
char 是长度为 1 的字符串。
"""
def sum_char(string, char):
    str1=list(string)
    count=0
    for i in range(len(string)):
        if str1[i] == char:
            count+=1
    return count
str2=str(input())
char1=str(input())
print(sum_char(str2, char1))


=====================================
文件扩展名
文件扩展名是操作系统用来标记文件类型的一种机制。通常来说,一个扩展名是跟在主文件名后面的,由一个分隔符(.)分隔。

请用程序实现
用函数实现,将文件的扩展名获取出来。

"""
获取文件扩展名
说明:实现 file_ext 函数,该函数接受一个表示文件名的字符串参数 filename,返回它的扩展名
"""
def file_ext(filename):
    str1=list(filename)
    for i in range(len(filename)):
        if str1[i]!=".":
            continue
        elif str1[i]==".":
            str2=str1[i+1:]
            str3=''.join(str2)
            return str3
            break
        else:
            return "error"

=====================================
以上内容可供初学者进行练习使用,欢迎大家转载转发,注明出处即可!

你可能感兴趣的:(python函数和代码的复用)