• 下午学习,函数部分相关内容


     1 #函数(function):有返回值
     2 #过程(procedure):是简单、特殊并且没有返回值的,python只有函数没有过程
     3 
     4 def hello():
     5     print("hello word")
     6 temp=hello() #这条语句显示结果为:hello word
     7 print(temp)#打印出来的结果是 none 这就是返回值
     8 
     9 def back():
    10     return[1,"中国山东",3.14]
    11 temp=back()
    12 print(temp)#通过打印才能显示出结果。这是列表。
    13 
    14 def back():
    15     return 1,"中国山东",3.14
    16 temp=back()
    17 print(temp)#通过打印才能显示出结果。这次是元组。
    18 
    19 #局部变量:Lock Variable
    20 #全局变量:Global Variable
    21 print("="*80)
    22 def discounts(price=89,rate=0.85):
    23     global final_price #在这里声明为全局变量后,在外部可以访问了。
    24     final_price=price*rate
    25     #print("这里试图打印全局变量old_price的值:",old_price)#局部能访问全局变量
    26     return final_price
    27 
    28 #old_price=float(input("请输入原价:"))
    29 #rate=float(input("请输入折扣率:"))
    30 new_price=discounts()#(old_price,rate),当input启用时,注释括号内的内容,应写到前面
    31 print("打折后的价格是:",new_price)
    32 #以上代码是一个计算折扣的完整代码。
    33 #print("这里试图打印局部变量final_price的值:",final_price) #外部不能访问局部变量
    34 #print("这里试图打印全局变量old_price的值:",old_price)
    35 print("="*80)
    36 count=5
    37 def Myfun():
    38     count=10
    39     print("这里打印是的函数内部的变量count:",count)
    40 Myfun()
    41 print("这里打印的是全局变量count",count)
    42 #怎么变成全局变量呢??声明为全局变量即可。global varible
    43 #内嵌函数:python里面允许函数里面创建另外一个函数。
    44 
    45 def fun1():
    46     print("fun1()正在被调用……")
    47     def fun2():
    48         print("fun2()正在被调用……")
    49     fun2()#这里一定要注意,要和上面的内嵌函数def对齐。要不,就不能正常调用。
    50 fun1()
    51 
    52 #闭包:(closure)是函数编程的重要的语法结构,是一种编程范式。
    53 
    54 def FunX(x):
    55     def FunY(y):
    56         return x*y
    57     return FunY
    58 i=FunX(8)
    59 jg=i(9)
    60 print("闭包函数的计算结果是:",jg)
    61 print("="*80)
    62 def Fun1():
    63     x=[7,8,9]
    64     print("这是外部函数")
    65     def Fun2():
    66         print("这是内部函数")
    67         nonlocal x #强制说明x不是局部变量
    68         x[1]*=x[1]
    69         return x[1]
    70         
    71     return Fun2()
    72 i=Fun1()
    73 print(i)
    74 
    75 print("="*80)
    76 def Fun1():
    77     x=15
    78     print("这是外部函数x=15")
    79     def Fun2():
    80         print("这是内部函数,得到x的平方")
    81         nonlocal x #强制说明x不是局部变量
    82         x*=x
    83         return x
    84         
    85     return Fun2()
    86 i=Fun1()
    87 print(i)
    88 print("="*80)
  • 相关阅读:
    VPython—旋转坐标系
    分布式锁简单入门以及三种实现方式介绍
    win10 64bit安装redis及redis desktop manager的方法
    Kafka史上最详细原理总结
    idea常用快捷键
    十大Intellij IDEA快捷键
    Spark(一): 基本架构及原理
    Idea Live Templates代码模板
    IntelliJ IDEA 常用快捷键列表及技巧大全
    Win10 下 RabbitMQ 的 安装 配置
  • 原文地址:https://www.cnblogs.com/bcyczhhb/p/10220932.html
Copyright © 2020-2023  润新知