13 python基础--变量
发布日期:2021-05-14 12:22:24 浏览次数:15 分类:精选文章

本文共 3837 字,大约阅读时间需要 12 分钟。

13.1 变量规则

局部变量和全局变量是不同变量。局部变量是函数内部的占位符,与全局变量可能重名但不同。函数运算结束后,局部变量被释放。可以使用 global 保留字在函数内部使用全局变量。

示例1:

n, s = 10, 100
def y(n):
global
for i in range(1, n+1):
s *= i
return sprint(y(n), s)
# 输出 > 362880000

示例2:

n, s = 10, 100
def y(n):
s = 1 # 局部变量
for i in range(1, n+1):
s *= i
return sprint(y(n), s)
# 输出 > 100

规则2:局部变量为组合数据类型且未创建,等同于全局变量。

规则3:Python 变量不需要声明变量类型,因为 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 有四种变量作用域:

  • 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 等)不会引入新的作用域,其内部定义的变量可以在外部访问。

示例:

if True:
msg = 'a'
print(msg)
# 输出 > a

示例:

def a():
msg_inner = 'I am from Runoob'
print(msg_inner)
# 输出 > NameError: name 'msg_inner' is not defined

当内部作用域想修改外部作用域的变量时,需使用 globalnonlocal 关键字。

示例:

def outer():
num = 10
def inner():
nonlocal num
num = 100
print(num)
inner()
print(num)
outer()
# 输出 > 100 > 100

注:若注釋 nonlocal num,则 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} > 全局变量...

eval() 函数

将字符串当作表达式执行,返回结果的字符串。语法:

eval(string_code, globals=None, locals=None)

exec() 函数

执行字符串代码,不返回结果。语法:

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
class Gap:
def __init__(self):
t.penup()
t.speed(1000)
t.fd(5)
def line(self, draw):
self.Gap()
t.speed(100)
t.pendown() if not draw else t.penup()
t.fd(40)
self.Gap()
t.right(90)
def num(x):
if x in [2, 3, 4, 5, 6, 8, 9]:
self.line(True)
else:
self.line(False)
if x in [0, 1, 3, 4, 5, 6, 7, 8, 9]:
self.line(True)
else:
self.line(False)
if x in [0, 2, 3, 5, 6, 8, 9]:
self.line(True)
else:
self.line(False)
if x in [0, 2, 6, 8]:
self.line(True)
else:
self.line(False)
t.left(90)
if x in [0, 4, 5, 6, 8, 9]:
self.line(True)
else:
self.line(False)
if x in [0, 2, 3, 5, 6, 7, 8, 9]:
self.line(True)
else:
self.line(False)
if x in [0, 1, 2, 3, 4, 7, 8, 9]:
self.line(True)
else:
self.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()))
t.hideturtle()
t.donemain()
上一篇:14 python基础--复用和递归
下一篇:12 python基础--函数

发表评论

最新留言

表示我来过!
[***.240.166.169]2025年04月08日 11时18分53秒