系统关键字
系统关键字
1、查看python系统保留关键字有哪些
打开windows命令行界面WIN+R,cmd>>
>> python
>> import keyword
>> keyword.kwlist
print函数用法
用法1:
有这样一个需求,把多行打印的内容,在一行打印
print("a")
print("b")
print("c")
例1:
print("a",end=" ")
print("b",end=" ")
print("c")
a b c
总结:print()函数默认end=“\n” 是换行,可以通过改变end的值,来改变print的结束符
用法2:
例2:对打印内容持久化保存到本地
print()支持将打印内容写入到文件对象里
f = open("demo.txt", "w")
print("hello world", file=f)
print("mily", file=f)
例3:
with open("demo2.txt", "w") as file_object:
print("demo2 file is being change", file=file_object)
用法3:
例4:
对多个变量进行分割
name = "mily"
age = 18
print(name, age, sep=" ***** ")
mily ***** 18
is 和 == 的区别
初学python,可能对is和==的理解不是很清楚,下面讲下两者的区别
== : 是python中的比较运算符,用来判断两个对象的value值是否相等。
is : 也叫同一性运算符,这个运算符比较判断的是对象间的唯一身份标识。用来比对两个变量引用的是否是同一个对象,也就是id是否相同。
例1:整形
# a和b为整形类型
a = 1
b = 1
print(a is b)
print(a == b)
print(id(a))
print(id(b))
True
True
2250138583280
2250138583280
例2:字符串
# a和b为字符串类型
a = 'mikezhou'
b = 'mikezhou'
print(a is b)
print(a == b)
print(id(a))
print(id(b))
True
True
2048828685616
2048828685616
例3:元祖
# a和b为元组类型
a = (1,2,3)
b = (1,2,3)
print(a is b)
print(a == b)
print(id(a))
print(id(b))
True
True
2701248236800
2701248236800
例4:列表
# a和b为list类型
a = [1,2,3]
b = [1,2,3]
print(a is b)
print(a == b)
print(id(a))
print(id(b))
False
True
2107004932864
2107007284224
结论:
,列表是可变的
1、当比较的变量是不可变类型,那is指向的是同一个对象地址 (整形、字符串、元祖是不可变数据类型)
2、列表支持扩展的,是可变的,is指向的不是同一个地址空间
推导式
1、列表推导式
例1:
list1 = [i for i in range(1, 101)]
print(list1)
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100]
例2:
list1 = [i * 2 for i in range(1, 101) if i < 20]
print(list1)
[2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30, 32, 34, 36, 38]
例3:
list1 = ["mily" for i in range(1, 101) if i<30]
print(list1)
['mily', 'mily', 'mily', 'mily', 'mily', 'mily', 'mily', 'mily', 'mily', 'mily', 'mily', 'mily', 'mily', 'mily', 'mily', 'mily', 'mily', 'mily', 'mily', 'mily', 'mily', 'mily', 'mily', 'mily', 'mily', 'mily', 'mily', 'mily', 'mily']
2、字典推导式
1、有这样一个需求把字典的key和value值对调
dict1 = {"a": 1, "b": 2, "c": 3}
new_dict = {value: key for key, value in dict1.items()}
print(new_dict)
{1: 'a', 2: 'b', 3: 'c'}
2、可以很灵活的对原有字典值进行调整
dict1 = {"a": 1, "b": 2, "c": 3}
new_dict = {value*2: key for key, value in dict1.items()}
print(new_dict)
{2: 'a', 4: 'b', 6: 'c'}
3、集合推导式
有这样一样需求,对列表里元素,去重,再乘以2
例1:
list01 = [1, 2, 2, 3, 2, 4, 3]
set01 = {i for i in list01}
print(set01)
{1, 2, 3, 4}
例2:
list01 = [1, 2, 2, 3, 2, 4, 3]
set01 = {i*2 for i in list01}
print(set01)
{8, 2, 4, 6}