Python基础(一)之变量

变量声明

1 #-*-coding:utf-8-*-
2 
3  name = "Brain Yang"

   上述代码声明了一个变量,变量名为: name,变量name的值为:"Brain Yang",下面讲一讲每一行

#-*-coding:utf-8-*-

  声明字符编码集:为了显示中文声明字符集 UTF-8,Python 2.x一定要声明,Python 3.x 默认为 UTF-8 可以不声明。

name = "Brain Yang"  #声明变量name

  声明变量声明了一个变量,变量名为: name,变量name的值为:"Brain Yang",该变量类型为字符串,用单引号 ('...') 或双引号 ("...") 标识。变量的命名规则如下。

 变量定义的规则:

      • 变量名只能是 字母、数字或下划线的任意组合
      • 变量名的第一个字符不能是数字
      • 以下关键字不能声明为变量名
        ['and', 'as', 'assert', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'exec', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'not', 'or', 'pass', 'print', 'raise', 'return', 'try', 'while', 'with', 'yield']

变量的赋值

1 name = "Alex Li"
2  
3 name2 = name 
4 print(name,name2)
5  
6 name = "Jack"
7  
8 print("What is the value of name2 now?")

 变量在使用前必须 “定义”(赋值),否则会出错:

>>> # try to access an undefined variable
... n
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'n' is not defined

 

 
原文地址:https://www.cnblogs.com/yz9110/p/8133965.html