小白的python学习之路(2)

变量与数据类型(一)

每一门程序语言都有变量,在python中:
变量–存储数据的容器,变量的值可以是任意一种数据类型
数据–字符串str、整型int、浮点型flaot、布尔boolean、列表list、元组tuple、字典dict、集合set
声明变量:
a = 1 # 此时将int(整型)类型赋值给变量a,此时a的值是1,类型是int类型,id可以通过解释器获取。
获取变量的值:print(a)
获取变量的类型:type(a)
获取变量的id:id(a)
此时又学了两个函数:type()函数,用于获取变量的类型,id()函数,用户获取变量的id
在这里插入图片描述
当创建一个数据时,该数据有id、type、value三部分组成,变量a指向的指示数据的值,当对变量重新赋值时,此时id也在变化,原数据出于python垃圾回收机制,被清除,即上图右侧的框被回收。出现新的字符串数据-下图例子:
在这里插入图片描述
此时a的值变成了字符串’abc’,id也发生了变化。
再来一个例子:
a = b = 8,此时a的值与b的值都是8,数据类型都是int类型,id也是相同的。
在这里插入图片描述
变量的命名规则:
1、下划线、字母开头,由数字、字母、下划线组成。
符合规则:
a
abcf
name
_age 但通常不这么命名
first_name 两个单词组合时,用下划线连接
person3
不符合规则:
1abc
abc$b
命名时–
2、要做到见字识意,比如name、age、gender、dog,尽量不要胡乱起名。
3、不可以是python的保留字
在这里插入图片描述
查询保留字方法:
导入keyword模块 import keyword
调用kwlist方法 keyword.kwlist
当保留字被引号括起来时,此时是字符串,而不是保留字

小技巧:
python之禅:
import this

The Zen of Python, by Tim Peters

Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren’t special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you’re Dutch.
Now is better than never.
Although never is often better than right now.
If the implementation is hard to explain, it’s a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea – let’s do more of those!

错误分析:
SyntaxError: invalid syntax 无效语法
SyntaxError: EOL while scanning string literal 引号没有成对出现

猜你喜欢

转载自blog.csdn.net/zhangchen10086/article/details/107119511