【Python】变量类型、变量命名规则和注释

1.变量类型

(1)整型
3.x版本只有int这一种,支持二进制表示法,如0b100(二进制)

Python2.x中有int和long两种整型
type(变量名)函数可以查看变量的类型,python中定义变量不用写类型和分号

a = 100
a2 = 0b1110  #二进制
a3 = 0x1110    #十六进制

print(type(a))     #<class 'int'>
print(a2)    #14
print(type(a2))    #<class 'int'>

(2)浮点型
也就是小数,如123.456,还支持科学计数法(1.23456e2)。

b = 12.345
b2 = 1.23456e2
print(type(b))     #<class 'float'>
print(b2)    #123.456

(3)字符串型
单引号或双引号括起来的任意文本,如'hello',"hello"。

d = 'hello,world'
d2 = "hello,world"
print(type(d))     #<class 'str'>
print(type(d2))     #<class 'str'>

(4)布尔型
结果只有True、False这两种值。

e = True    #注意是大写
print(type(e))     #<class 'bool'>

(5)复数型
如:3+5j,和数学上的复数表示一样,虚部换成了j,这个类型较少使用。其中 j2 = -1

c = 1+5j
print(type(c))     #<class 'complex'>

2.变量命名规则

  • 硬性规则
    • 变量名由字母、数字和下划线构成,数字不能开头
    • 大小写敏感(大写的A和小写的a是两个不同的变量)
    • 不要和关键字(print...)、系统保留字冲突
  • PEP 8要求
    • 用小写字母拼写,多个单词用下划线连接xxx_yyy_zzz
    • 受保护的实例属性用单个下划线开头
    • 私有的实例属性用两个下划线开头

Python 采用 PEP 8 作为编码规范,其中 PEP 是 Python Enhancement Proposal(Python 增强建议书)的缩写,8 代表的是 Python 代码的样式指南。

3.注释

(1)单行注释
#开头

# 你好世界
print("hello,world")

(2)多行注释
三个引号开头和三个引号结尾,单引号双引号都可以。
多行注释可作为字符串

'''
    版本:1.0
    作者:张三
'''
print("hello,world")

"""
    版本:1.1
    作者:李四
"""
print("hello,world!")
posted @ 2022-09-09 14:56  植树chen  阅读(239)  评论(0编辑  收藏  举报