Python变量

  • 变量:在程序运行过程中,值会发生变化的量。
  • Python中的变量不需要声明类型
  • 用“=”号来给变量赋值
  • 每个变量在使用前都必须赋值,变量赋值以后才会被创建。即:新的变量通过赋值的动作,创建并开辟内存空间,保存值。如果没有赋值而直接使用会抛出赋值前引用的异常或者未命名异常。
  • 在Python中,变量本身没有数据类型的概念。即:通常所说的“变量类型”是变量所引用的对象的类型,或者说是变量的值的类型。
  • “=”号这个赋值运算符是从右往左的计算顺序
  • Python允许同时为多个变量赋值
  • ! 请牢记:Python中的一切都是对象,变量是对象的引用!

2.1. 变量命名规则:

1.不以下划线为开头,如_user等(有特殊含义);

2.变量命名容易读懂:如user_name

3.不适用标准库中内置的模块名或者第三方的模块名称;

4.不要用python内置的关键字:

In [3]: import keyword

In [4]: keyword.kwlist
Out[4]:
['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']

2.2. 如何理解python变量赋值

s = 'hello'
#变量名 s 分配给 hello 这个对象


hello 这个对象会先在内存中创建出来,然后再把变量名 s 分配给 此对象。

所以python中变量赋值,应始终看 等号右边

2.3. 多元赋值

In [8]: n1, n2 =1, 2

In [9]: n1
Out[9]: 1

In [10]: n2
Out[10]: 2

In [11]: n1 = 1, 2

In [12]: n1
Out[12]: (1, 2)
In [13]: s1, s2 = '12'  #序列类型数据

In [14]: s1
Out[14]: '1'

In [15]: s2
Out[15]: '2'
In [16]: num, s = [10, 'hello'] #列表

In [17]: num
Out[17]: 10

In [18]: s
Out[18]: 'hello'

2.4. python中的判断

In [1]: n =10

In [2]: n == 10 #判断n等于10
Out[2]: True #条件为真,返回True

In [3]: n != 10 #判断n不等于10
Out[3]: False #条件为假,则返回False

In [4]: n > 10 #大于
Out[4]: False

In [5]: n < 10 #小于
Out[5]: False

In [6]: n >= 10
Out[6]: True

In [7]: n <= 10
Out[7]: True
In [10]: n = input("请输入一个数字>>:")
请输入一个数字>>:10

In [11]: n == 10
Out[11]: False

In [12]: n
Out[12]: '10' #'10'字符串

上述判断会发现返回结果为 False

在编程语言中,数据是有类型之分的。

input() 在接受到任何数据都会成为 字符串类型(str),即普通字符串

而等号右边的 10 是整型(int)

如:
In [13]: '10' == 10
Out[13]: False

In [14]: '10' > 10
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-14-a2286912985a> in <module>
----> 1 '10' > 10

TypeError: '>' not supported between instances of 'str' and 'int'
#字符串和整型无法比较