zoukankan      html  css  js  c++  java
  • python 高级语法 函数(一)

    前言:

    圆的面积计算公式为:

    S = πr2

    假设我们需要计算3个不同半径的圆的面积:

    r1 = 1.1
    r2 = 2.2
    r3 = 3.3
    s1 = 3.14 * r1 * r1
    s2 = 3.14 * r2 * r2
    s3 = 3.14 * r3 * r3
    
    

    观察 s1,s2,s3 的计算过程,π 的值 3.14 是不变的,只是半径变而已,所以计算的过程中就会出现重复使用 π。

    写一个圆面积计算函数:

    def area_of_circle(x):
        return 3.14*x*x  # x 为半径
    
    
    r = area_of_circle(1.1)  # 调用 area_of_circle 函数,只需要输入半径即可
    print(r)
    

    函数area_of_circle本身只需要写一次,就可以多次调用。

    Python不但能非常灵活地定义函数,而且本身内置了很多有用的函数,可以直接调用。


    抽象

    抽象是数学中非常常见的概念。举个例子:

    计算数列的和,比如:1 + 2 + 3 + ... + 100,写起来十分不方便,于是数学家发明了求和符号∑,可以把1 + 2 + 3 + ... + 100记作:

    100
    ∑n
    n=1
    

    这种抽象记法非常强大,因为我们看到 ∑ 就可以理解成求和,而不是还原成低级的加法运算。

    而且,这种抽象记法是可扩展的,比如:

    100
    ∑(n2+1)
    n=1
    

    还原成加法运算就变成了:

    (1 x 1 + 1) + (2 x 2 + 1) + (3 x 3 + 1) + ... + (100 x 100 + 1)
    

    可见,借助抽象,我们才能不关心底层的具体计算过程,而直接在更高的层次上思考问题。



    函数的使用

    1. 定义函数
    def 函数名(参数):
        代码1
        代码2
        return 表达式 
    

    定义函数的过程中,需要注意以下几点:

    • 函数代码块以def关键词开头,一个空格之后接函数标识符名称和圆括号(),再接个冒号。
    • 任何传入的参数必须放在圆括号中间。
    • 函数内容以冒号起始,并且缩进。
    • 使用return结束函数。默认返回None。
    • return语句依然在函数体内部,不能回退缩进。直到函数的所有代码写完,才回退缩进,表示函数体结束。


    如何调用函数

    函数写出来就是给其他地方调用的,要调用一个函数,必须使用函数名后跟圆括号的方式才能调用函数。

    函数名(参数)
    

    根据实际情况,参数可有可无。

    先定义函数,后调用函数。


    函数的参数作用

    完成需求如下:完成两个数 3 和 5 的相加

    # 定义函数
    def add():
        return 3 + 5
    
    print(add())  # 调用函数
    

    上诉函数只完成了 3 和 5 的相加,如果想要这个函数变得更灵活,可以计算任何用户指定的两个数字的和,要进行以下修改。

    把两个值设置为变量

    # 定义函数时同时定义了接收用户数据的参数a和b,a和b是形参
    def add(a, b):
        return a + b
    
    print(add(3, 8))  # 调用函数的时候,需要传入两个参数,分别传给 a 和 b
    

    • 形参:函数定义时书写的参数(非真实数据)
    • 实参:函数调用时书写的参数(真实数据)
    def add(a, b):
        return a + b
    
    x, y = 8 ,9
    
    print(add(x, y))  # 17    使用变量,传递参数。
    print(add(8, 9))  # 17    直接传递值也是可以的。
    
    

    在上面的例子中,a,b叫做形式参数,简称形参。
    而x,y和8,9 叫做实际参数,简称实参,也就是实际要传递的值。
    我们通常讨论的参数,指的都是形参。



    函数嵌套使用

    def testB():
        print('---- testB start----')
        print('这里是testB函数执行的代码......')
        print('---- testB end----')
    
    def testA():
        print('---- testA start----')
        testB()  # 调用函数testB
        print('---- testA end----')
    
    testA()
    """
    执行结果:
    ---- testA start----
    ---- testB start----
    这里是testB函数执行的代码......
    ---- testB end----
    ---- testA end----
    
    """
    
    


    执行流程:
    遇到函数不执行,调用函数才执行。

    1. 首先调用了函数 testA()
    2. 执行testA()函数的过程中,遇到函数 testB()
    3. 调用了函数 testB(),执行 testB()


    函数的应用

    计算三个数之和

    def sum_num(a, b, c):
        return a + b + c
    
    
    result = sum_num(1, 2, 3)
    print(result)  # 6
    
    

    计算三个数的平均值

    def sum_num(a, b, c):
        return a + b + c
    
    
    def average_num(a, b, c):
        sumResult = sum_num(a, b, c)
        return sumResult / 3
    
    result = average_num(1, 2, 3)
    print(result)  # 2.0
    
    

    随机生成20个学生的成绩,判断这20个学生成绩的等级.

    import random
    
    
    def get_level(score):
        if 90 < score <= 100:
            return '非常优秀'
    
        elif 80 < score <= 90:
            return '优秀'
    
        elif 60 < score <= 80:
            return '及格'
    
        else:
            return '不及格'
    
    
    def main():
        # scores = []
        # 生成所有的成绩;
        # for count in range(20):
        #     scores.append(random.randint(1, 100))
    
        for i in range(20):
            score = random.randint(1, 100)
            # 调用函数
            level = get_level(score)
            print("成绩:%s, 等级: %s" % (score, level))
    
    
    if __name__ == "__main__":
        main()
    


    使用python实现简单计算器的功能

    
    # 定义函数
    def add(x, y):
        """加法"""
        return x + y
    
    
    def subtract(x, y):
        """减法"""
        return x - y
    
    
    def multiply(x, y):
        """乘法"""
        return x * y
    
    
    def divide(x, y):
        """除法"""
        return x / y
    
    
    def number():
        num1 = int(input("请输入运算的第一个数字:\n"))
        num2 = int(input("请输入运算的第二个数字:\n"))
        return num1, num2
    
    
    if __name__ == '__main__':
        while 1:
            # 用户输入
            print("选择运算方式:1、加法;2、减法;3、乘法;4、除法;5、退出")
            choice = int(input("请选择运算方式(1/2/3/4/5):\n"))
    
            # num1 = int(input("请输入运算的第一个数字:"))
            # num2 = int(input("请输入运算的第二个数字:"))
    
            # 选择1就是加法,调用加法的函数
            if choice == 1:
                num1, num2 = number()
                result = add(num1, num2) # 调用函数
                print("%d + %d = %2d" % (num1, num2, result))
    
            # 选择2就是减法,调用减法的函数
            elif choice == 2:
                num1, num2 = number()
                result = subtract(num1, num2)  # 函数调用
                print("%d - %d = %2d" % (num1, num2, result))
    
            elif choice == 3:
                num1, num2 = number()
                result = multiply(num1, num2)
                print("%d * %d = %d" %(num1, num2, result))
    
            elif choice == 4:
                num1, num2 = number()
                result = divide(num1, num2)
                print("%d / %d = %s" %(num1, num2, result))
    
            elif choice == 5:
                print("end!")
                break
    
            else:
                print("非法输入,请输入正确的运算方式!")
    
    


    完成注册,登录,退出系统功能

    
    def userN():
        username = input("请输入账号: \n")
        password = input('请输入密码: \n')
        return username,password
    
    
    def register():
        # 注册函数封装
        username,password= userN()
        temp = username + "|" + password
        with open('D:\\1221\\Test_Python\\login.md','w') as file:
            file.write(temp)
    
    
    def login():
        # 登录函数封装
        username,password = userN()
        with open('D:\\1221\\Test_Python\\login.md') as file:
            user = file.read().split("|")
        if username == user[0] and password == user[1]:
            print("登录成功!")
            getNick()  # 跳转到主页面
            # return '登录成功'
    
        elif username == user[0] and password != user[1]:
            print("输入密码有误,请重试!")
    
        elif username != user[0] and password == user[1]:
            print("输入账号有误,请重试!")
    
        elif username == "" or password == "":
            print("输入账号或密码为空,请重试!")
    
        else:
            print("登录失败,请检查账号或者密码!")
            # return '登录失败,请检查账号或者密码'
    
    
    def getNick():
        # 查看个人主页
        with open('D:\\1221\\Test_Python\\login.md') as file:
            user = file.read().split("|")
            print('%s您好,欢迎再次回来!' % (user[0]))
    
    
    def exit():
        # 退出系统
        import sys
        print('系统已退出,欢迎下次再登录!')
        sys.exit(1)
    
    
    def Main():
        while True:
            put = int(input('请选择 1.注册 2.登录 3.退出系统'))
            if put == 1:
                # 调用注册函数
                register()
    
            elif put == 2:
                # 调用登录函数
                login()
                # getNick()  # 跳转到主页面
    
            elif put == 3:
                # 调用退出函数
                exit()
    
            else:
                print('输入错误,请重新输入...')
                continue
    
    
    if __name__ == '__main__':
        Main()
    
    
  • 相关阅读:
    nested exception is java.lang.NoClassDefFoundError: org/springframework/web/servlet/mvc/method/annotation/RequestMappingHandlerAdapter
    Java 四种线程池newCachedThreadPool,newFixedThreadPool,newScheduledThreadPool,newSingleThreadExecutor
    技术笔记:多线程(Runnable)类或者是监听器中使用Autowired自动注入出现null的问题
    java获取本机IP
    [Java基础]StringUtils.join()方法与String.join()方法的使用
    SpringBoot bootstrap.yml bootstrap.properties 配置未生效
    ((TextBox)(GridView1.Rows[GridView1.EditIndex].Cells[1].Controls[0])).Text; 转换出错、获取不到值的解析 Asp.net
    C# 调用 origin 批量作图
    c# 调用R语言 实现线性拟合 方差 Ftest概率检验求p-value
    c#对象深复制 序列化与反序列化
  • 原文地址:https://www.cnblogs.com/wwho/p/15698320.html
Copyright © 2011-2022 走看看