Python初级认知--标识符、变量

缘起上文:工欲善其事必先利其器--Python学前准备gVim

 

万事以备,接下来开始我们Python核心内容的学习。

本次目标:

一、 两种常用方式

1. 使用 REPL

REPL 即 R(read)、E(evaluate)、P(print)、L(loop)缩写,就是交互模式。

2. 使用文件

1) 、 GVIM 编辑文件

2)、运行文件

二、 编程规范

“ 合理注释 、 适当缩进 、 成对编程”基本的风格 ,保持编写代码时“ 见名知意”的常用手段 。

1、  合理 注释

我们阅读文学时,免不了留意过文骚墨客留下的诗词曲阜,年代久远,为了让我们看明白,一般都会为诗词留下年代以、创作环境及如何解释。试想我们写代码,事件久了,别说别人读半天不知道干啥的,就是我们自己也未必想起当时的逻辑,你能想象自己有一天拿到的代码没有一个解释是多么的坑吗?别坑队友,更别坑自己。我们截取一段 JSON 中的源码。这就是你的目标。

def __init__(self, skipkeys=False, ensure_ascii=True,
check_circular=True, allow_nan=True, sort_keys=False,
indent=None, separators=None, encoding='utf-8', default=None):
"""Constructor for JSONEncoder, with sensible defaults.
If skipkeys is false, then it is a TypeError to attempt
encoding of keys that are not str, int, long, float or None. If
skipkeys is True, such items are simply skipped.
- 3 -
If *ensure_ascii* is true (the default), all non-ASCII
characters in the output are escaped with \uXXXX sequences,
and the results are str instances consisting of ASCII
characters only. If ensure_ascii is False, a result may be a
unicode instance. This usually happens if the input contains
unicode strings or the *encoding* parameter is used.
If check_circular is true, then lists, dicts, and custom encoded
objects will be checked for circular references during encoding to
prevent an infinite recursion (which would cause an OverflowError).
Otherwise, no such check takes place.
If allow_nan is true, then NaN, Infinity, and -Infinity will be
encoded as such. This behavior is not JSON specification compliant,
but is consistent with most JavaScript based encoders and decoders.
Otherwise, it will be a ValueError to encode such floats.
If sort_keys is true, then the output of dictionaries will be
sorted by key; this is useful for regression tests to ensure
that JSON serializations can be compared on a day-to-day basis.
If indent is a non-negative integer, then JSON array
elements and object members will be pretty-printed with that
indent level. An indent level of 0 will only insert newlines.
None is the most compact representation. Since the default
item separator is ', ', the output might include trailing
whitespace when indent is specified. You can use
separators=(',', ': ') to avoid this.
If specified, separators should be a (item_separator, key_separator)
tuple. The default is (', ', ': '). To get the most compact JSON
representation you should specify (',', ':') to eliminate whitespace.
- 4 -
If specified, default is a function that gets called for objects
that can't otherwise be serialized. It should return a JSON encodable
version of the object or raise a ``TypeError``.
If encoding is not None, then all input strings will be
transformed into unicode using that encoding prior to JSON-encoding.
The default is UTF-8.
"""
self.skipkeys = skipkeys
self.ensure_ascii = ensure_ascii
self.check_circular = check_circular
self.allow_nan = allow_nan
self.sort_keys = sort_keys
self.indent = indent
if separators is not None:
self.item_separator, self.key_separator = separators
if default is not None:
self.default = default
self.encoding = encoding

后期阅读源码,发现优秀的代码大量的注释,甚至注释比代码多。


注释分类:
1)单行注释: 以#开始,遇到#该行后的所有内容为注释内容(引号中的除外)。可以单独一行,也可以在代码的后面。

python print("看我我,咱们就正式开始学习 python 了") # 注释 1

2)文档注释(docstring):注释多行'''注释内容'''或"""注释内容""",多行注释不要相互嵌套。

2 、正确缩进 【 规则 】

python 中使用 tab 键来组织代码,保持正确的缩进。

在 python 中缩进时语法内容,是程序的生命!

3 、成对编程

在编写() “” ‘’ [] 是,成对编写,后再插入代码。

4 、见名知意

以后命名的地方务必见名知意,如 name gender hobby find_object_by_id,同时我们的命名区分大小写:name Name 和 NAME 都不同,大多数情况都是使用小写。

5 、避免中文

让你别写就别写,除非非用不可,要不何必执拗。

三、 标识符

标识符即名字,也称为助记符。Python 里给变量名、函数名、类名、包名起名字。我们python的命名规则,必须遵循语法规则和命名规范。

1 、命名规则( 不遵守运行错误)

a) 组成

b) 关键字
标识符不能是系统的关键字和保留字,关键字和保留字全部“专供 特供”系统内部使用,所以: if、where、str 都是错误的。
导入工具箱 : import keyword keyword.kwlist

2 、命名规范

a)、变量、函数、包名、模块名: 小写字母,单词之间用分割 如:box、max_age、regex_syntax,pycompile
b)、类名、异常名: W 驼峰,单词首字母全部大写,其他字母小写 如 TypeError,BlackTea
c)、实例变量等内部:以开头、小写字母组成以及单词用分割
d)、全局或者类常量,全部使用大写字母,并且以下划线分隔单词;如:MAX_LOAD(其实 python 内部没有机制保证常量值不会改变)

四、 变量

Python 不是像 C++或者 java 那样是强类型语言,属于弱类型语言,python 把变量看成一个万能的盒子,可以装各种东西(数据),盒子的名字就是变量名,盒子的内容就是变量的数据。

变量其实是计算机内存中的一块区域,变量可以存储规定范围内的值。

1. 赋值

1) 格式

变量名 = 值;
变量名 1,变量名 2,变量名 3 …= (值 1,值 2,值 3…)
变量名 1=变量名 2=...=变量名 n=值

如:

book_name=’python 基础’
x,y,z = (1,2,3)
a = b =c =0
a ,b = 1,2
a,b =b,a #交换了吗?

2) 内部结构

使用 id(变量或者值)查看存储的内存地址,初始显示是十进制,可以使用 hex(十进制值),转为十六进制。

>>>y = 1
>>> id(y)
1846832176
>>> hex(id(y))
'0x6e146c30'

在系统内部,字符串常量和 int 类型字面值在内存中存放在常量池中共享。

2. 局部变量

函数内部声明变量是局部变量,局部变量只能在定义的函数内部,并且只能从声明一下可以使用,函数外和函数内变量声明以前不能使用或者调用局部变量

def var01():
num=10 #num 为局部变量
print num

运行:

>>> var01()
10
>>> print num #函数外调用
Traceback (most recent call last):
File "<pyshell#6>", line 1, in <module>
print num
NameError: name 'num' is not defined

在函数内,num 声明前使用 num 看看会发生什么

def var01():
print num
num=10 #num 为局部变量
print num

用 调用 var01() 观察结果:

>>> var01()
Traceback (most recent call last):
File "<pyshell#9>", line 1, in <module>
var01()
File "<pyshell#8>", line 2, in var01
print num
UnboundLocalError: local variable 'num' referenced before assignment

3. 全局变量

函数外声明的变量成为全局变量,全局变量可以在函数外调用,可以在函数内部查调用。

>>> g_a=100
>>> def test02():
print g_a
>>> test02()
100

注意观察下边的代码,猜测结果:

>>> def test03():
print g_b
>>> g_b=200
>>> test03()

运行对比猜测和运行结果是否一致。若是一致跳过这部分,不一致,我们来解释一下,若是你认为会报错,那么此刻你讲 test03()这行代码与 g_b=200 两行调换再运行,你会发现程序报错,认真读报错的信息。

NameError: global name 'g_b' is not defined

也就是说你声明的函数里使用了全局变量,此刻我们程序不检查,只要当调用该函数时,程序才会在作用域内查找变量是否定义。那么若是函数内部声明的变量与全局变量同名那么调用顺序是什么呢?

1.3 全局变量与局部变量重名

>>> num=100
>>> def test05():
num=20
print num
>>> test05()
20
>>> num
100

遵循就近原则,在函数内部使用变量(查看值,除了赋值,函数内第一次赋值就是变量的定义),先从函数内部查找变量的定义,若是没有找到,则向函数外部查找是否有该变量的定义,没找到则报变量没定义的异常。若是同名,则在函数内使用局部变量。如何在函数内部定义全局变量并且使用呢?使用 global 关键字,如下。

>>> def test10():
global bb
bb=-1
print bb
>>> test10()
-1
>>> bb
-1

注意
使用 global 修饰的局部变量,成为全局变量,若是全局有同名的变量,则属于对全局变量的修改或者使用。

列表和字典作为全局变量,在函数内部为该全局变量追加元素或者删除元素,则无需使用 global 关键字。

>>> nums=[1,2,3,4] #给列表追加元素
>>> def test11():
nums.append(6)
>>> test11()
>>> nums
[1, 2, 3, 4, 6]
>>> infos={'name':'zs'} #字典
>>> def test13():
infos['age']=18
>>> test13()
>>> infos
{'age': 18, 'name': 'zs'}

试想在函数内部使用 nums=[11]这样的,调用函数是否可以达到修改 nums 的目的?

今日分享内容到这,马上进入视频环节:

 

下一篇,我们聊聊内置工具、基本数据类型和小练习。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值