Python中的变量类型有:

int:带正负号的整数
long:在python2中表示长整数,在python3中被放弃
complex:复数
str:字符串
True,False:布尔
list:列表
dict:字典

 

查看变量类型type()
>>> a=10
>>> b=10.1
>>> type(a)
<type 'int'>
>>> type(b)
<type 'float'>

i1= 1
print(i1.bit_length())
1

i2 = 10
print(i2.bit_length())
4

bit_length()方法可以显示十进制转换成二进制时所占的有效位数

 

解压赋值
lst = [1,2,3,4]
a,b,c,d = lst
print(a,b,c,d)
1 2 3 4

如果只想取第1个和最后一个值,中间的变量名可以用下划线表示,下划线表示不会调用这个变量。
a, _, _, d = lst
print(a,d)
1 4

如果中间有很多个值,写多个_也不方便,可以使用*_表示多个
a, *_, d = lst
print(a,d)
1 4

变量名命名规范
1、变量名由字母、数字和下划线的任意组合组成
2、变量名不能以数字开关
3、变量名不能用关键字命名
4、可以使用驼峰法和下划线法命名,推荐用下划线法,比较清晰
5、变量名尽量使其有意义,宜精简易懂,不宜太长
6、变量名尽量不要使用中文命令
7、约定俗成用全部大写字母命名的变量名来表示常量

命名方式有
小驼峰命名法 userName
大驼峰命名法 UserName
下划线连接法 user_name

查看Python中有哪些关键字
import keyword
print(keyword.kwlist)

['False', 'None', 'True', 'and', 'as', 'assert', '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']

 

变量类型的转换

函数 解释
int() 将对象转换为整数,例如int(10)为10,不能是字母或浮点数
float() 将对象转换成浮点数,例如float(10.1)或float('10.1')结果都为10.1
complex() 将对象转换成复数,例如complex(10.1)或complex('10.1')结果都为(10.1+0j)
str() 将对象转换成字符串,例如str(10)为'10'
repr()

将对象转换为供解释器读取的形式,例如repr('hello')为"'hello'",
dict = {'runoob': 'runoob.com', 'google': 'google.com'};
repr(dict)结果为"{'google': 'google.com', 'runoob': 'runoob.com'}"

tuple()  将对象转换为元组,例如a='hello',tuple(a)为('h', 'e', 'l', 'l', 'o')
list()  将对象转换为列表,例如a='hello',list(a)为['h', 'e', 'l', 'l', 'o']
hex()  将对象转换为16进制,a必须是int类型,例如hex(10)为'0xa'
oct()  将对象转换为8进制,a必须是int类型,例如oct(10)为'0o12'
ord()   将对象转换为ASCII中对应的数字,例如ord(a)为97
chr() 将数字转换为ASCII中对应的值,例如chr(97)为a, chr(65)为A
posted on 2018-10-18 14:48  longfei2021  阅读(115)  评论(0编辑  收藏  举报