zoukankan      html  css  js  c++  java
  • python中函数的局部变量

    1、

    def discount(price,rate):     ## 定义函数名discount,两个形式参数price和rate
        sell_price = price * rate
        return sell_price        ## 函数返回售价
    price = float(input("please input the price:"))    ## 此处接受输入原价
    rate = float(input("please input the rate:"))      ## 此处接受输入折扣率
    final_price = discount(price,rate)                 ## 调用discount函数,使用位置参数
    print("the price after discount is %.2f:" % final_price)    ##  输出最终价格
    ## 以上函数, price、rate、final_price为全局变量, sell_price为局部变量
    please input the price:800
    please input the rate:0.6
    the price after discount is 480.00:

    2、

    def discount(price,rate):
        sell_price = price * rate
        return sell_price
    price = float(input("please input the price:"))
    rate = float(input("please input the rate:"))
    final_price = discount(price,rate)
    print("the price after discount is %.2f:" % final_price)
    print("output sell_price:",sell_price)   ## 此处尝试调用局部变量
    please input the price:800
    please input the rate:0.6
    the price after discount is 480.00:
    Traceback (most recent call last):     
      File "D:/programs/python/Lib/idlelib/a.py", line 8, in <module>
        print("output sell_price:",sell_price)
    NameError: name 'sell_price' is not defined     ## 不能调用局部变量

    3、

    def discount(price,rate):
        sell_price = price * rate
        print("please show the price again:", price)
        print("please show the rate again:",rate)
        return sell_price
    price = float(input("please input the price:"))
    rate = float(input("please input the rate:"))
    final_price = discount(price,rate)    ## 在调用discount函数时,调用了全局变量price和rate
    print("the price after discount is %.2f:" % final_price)
  • 相关阅读:
    python 批处理excel文件实现数据的提取
    python 实现excel数据的提取和整理
    正则表达式
    The zen of python
    恶作剧程序之炸弹窗口
    C 坦克射击小游戏
    C 查找数的位置
    niit源码--Developing java applications using servlet and jsp1
    框架
    设置多页面登陆,注册,递交
  • 原文地址:https://www.cnblogs.com/liujiaxin2018/p/14480843.html
Copyright © 2011-2022 走看看