关于python:Python自动化2Python变量

8次阅读

共计 1710 个字符,预计需要花费 5 分钟才能阅读完成。

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'

以上就是本次分享的全部内容,当初想要学习编程的小伙伴欢送关注 Python 技术大本营,获取更多技能与教程。

正文完
 0