08-变量与保留字

08-变量与保留字


一:保留字

使用以下代码查看Python中的保留字

演示:

import keyword
print(keyword.kwlist)

输出:

['False', 'None', 'True', 'and', 'as', 'assert', 'async', 'await', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise', 'return', 'try', 'while', 'with', 'yield']

这些保留字一般都不能用作标识符

二:标识符

  1. 什么叫标识符

    变量、函数、类、模块和其他对象起的名字就叫标识符

  2. 标识符命名规则

    • 只能用字母、数字、下划线命名
    • 不能用数字开头
    • 不能是保留字
    • 严格区分大小写

三:变量

  1. 什么是变量

    变量是内存中一个带标签的盒子。

  2. 变量的定义与使用

    • 变量由三部分组成

      1. 标识:表示对象所存储的内存地址,用 id( obj ) 获取
      2. 类型:对象的数据类型,使用 type( obj ) 获取
      3. 值:对象存储的具体数据,使用 print( obj ) 直接打印出
    • name = “桂桂”

      解析:

      ​ *name:*标识符,也就是变量名

      ​ *=:*赋值运算符

      ​ *桂桂:*给变量的值

  3. 变量的多次赋值

    • 变量可以多次赋值,新的值会覆盖旧的值

演示:

# 变量
name = "桂桂";
print("内存地址:",id(name))
print("类型:",type(name))
print("值:",name)

# 多次赋值
age = 1234;
print("id:",id(age)," type:",type(age)," 值:",age)
age = 5678;
print("id:",id(age)," type:",type(age)," 值:",age)

输出:

内存地址: 2537550061808
类型: <class 'str'>
值: 桂桂

id2537544939152  type<class 'int'>  值: 1234
id2537551076816  type<class 'int'>  值: 5678

猜你喜欢

转载自blog.csdn.net/qq_51248309/article/details/133093810