13 python基础--变量

13.1 变量规则

规则1:局部变量和全局变量是不同变量
-局部变量是函数内部的占位符,与全局变量可能重名但不同
-函数运算结束后,局部变量被释放
-可以使用global保留字在函数内部使用全局变量
n,s =10,100
def y(n):
    global            ##定义全局变量
    for i in range(1,n+1):
        s *= i
    return s
print(y(n),s)
>362880000 362880000
n,s =10,100
def y(n):
    s = 1            ##局部变量
  for i in range(1,n+1):
        s *= i
    return s
print(y(n),s)
>362880000 100
规则2:局部变量为组合数据类型且未创建,等同于全局变量
规则3:python 变量不需要声明变量类型,这是因为 C和 Java 语言是静态的,而 python 是动态的,变量的类型由赋予它的值来决定
l = [1,2,3,4,5]
def y(a):
    l.append(a)
    return

y(6)
print(l)
>[1, 2, 3, 4, 5, 6]
l = [1,2,3,4,5]
def y(a):
    l = []
    l.append(a)
    return

y(6)
print(l)
>[1, 2, 3, 4, 5]

13.2 变量作用域

python有4种变量作用域:
- Local 局部作用域
- Enclosing 闭包函数外的函数中
- Global 全局作用域   
- Built-in  内建作用域。
x = int(2.9)  # 内建作用域
g_count = 0  # 全局作用域
def outer():
    o_count = 1  # 闭包函数外的函数中
    def inner():
        i_count = 2  # 局部作用域

**Python 中只有模块(module),类(class)以及函数(def、lambda)才会引入新的作用域,其它的代码块(如 if/elif/else/、try/except、for/while等)不会引入新的作用域,这些语句内定义的变量,外部也可访问
if True:
    msg = 'a'
print(msg)
>a   # 外部可访问
def a():
    msgg_inner = 'I am from Runoob'
msg_inner
>NameError: name 'msg_inner' is not defined   #外部不可访问
当内部作用域想修改外部作用域的变量时,就要用到global和nonlocal关键字了
def outer():
    num =10
    def inner():
        nonlocal  num
        num = 100
        print(num)
    inner()
    print(num)
outer()
>>100
>>100   # 将 nonlocal num 注释时,此结果为10

13.3 变量与内存

C/C++:变量名称实际上是代表的一块内存区域。对该变量赋值的意思就是将新的值放入该变量指定的内存区域。即:变量名和内存区域的相应关系不会变,变的仅仅是相应内存中存放的值
python:全部的变量都是对内存区域的引用,对变量赋值相当于将变量引用的内存从一块区域改变到另外一块存放新值的区域。即:变量值的改变不是变量指向的内存区域值发生了变化,而是变量引用了新的存放新值的内存区域。

python中的全部变量都是相当于java中的不可变的变量,不论什么一次值的改变都相应着变量引用内存区域的变化。
a = 100
print(id(a))
a = 200
print(id(a))
>1437759600
>1437762800

13.4 内部函数

#####globals()和locals()

a = 1
b = 2
def fun(c,d):
    e = 111
    print('locals = {}'.format(locals()))
    print('globals = {}'.format(globals()))
    
fun(100,200)
>locals = {'e': 111, 'd': 200, 'c': 100}
>globals = {......}
eval()函数
把一个字符串当成一个表达式来执行, 返回表达式执行后的结果
语法:
      eval(string_code, globals=None, locals=None)
exec()函数
跟eval功能类似, 但是,不返回结果
语法:
  exec(string_code, globals=None, locals=None)
a = 100
b = 200
y = a + b 
print(eval('a+b'))
print(exec('a+b'))
z = exec("print(a+b)")
>300
>None
>300

13.5 数字代码打印

import turtle as t
import time
def Gap():         ##  定义链接分隔
    t.penup()
    t.speed(1000)
    t.fd(5)
def line(draw):      ## 定义画线函数
    Gap()
    t.speed(100)
    t.pendown() if draw else t.penup()
    t.fd(40)
    Gap()
    t.right(90)
def num(x):          ## 定义画数字函数
    line(True) if x in [2, 3, 4, 5, 6, 8, 9] else line(False)
    line(True) if x in [0, 1, 3, 4, 5, 6, 7, 8, 9] else line(False)
    line(True) if x in [0, 2, 3, 5, 6, 8, 9] else line(False)
    line(True) if x in [0, 2, 6, 8] else line(False)
    t.left(90)
    line(True) if x in [0, 4, 5, 6, 8, 9] else line(False)
    line(True) if x in [0, 2, 3, 5, 6, 7, 8, 9] else line(False)
    line(True) if x in [0, 1, 2, 3, 4, 7, 8, 9] else line(False)
    t.left(180)   ## 为后续的数字做准备
    t.penup()
    t.fd(20)
def GetDate(date):  ## 定义时间输出
    t.pencolor('red')
    for i in date:
        if i == '-':
            t.write('年',font=('楷体',18,'normal'))
            t.pencolor('green')
            t.fd(40)
        elif i == '=':
            t.write('月', font=('楷体', 18, 'normal'))
            t.pencolor('green')
            t.fd(40)
        elif i == '+':
            t.write('日', font=('楷体', 18, 'normal'))
        else:
            num(eval(i))
def main():
    t.setup(800,350,100,100)
    t.penup()
    t.fd(-300)
    t.pensize(6)
    GetDate(time.strftime('%Y-%m=%d+',time.gmtime())) ## 获取系统时间,并转化为'%Y-%m=%d+'格式
    t.hideturtle()      ## 隐藏箭头
    t.done
main()       ## 调用函数

猜你喜欢

转载自blog.csdn.net/qq_25672165/article/details/85059436