关于变量的比较
如果对同一个变量做多个and比较操作,python允许下面用法:
1<x<2
下面情况会被认为是False:
类型 | 值 |
---|---|
布尔 | False |
null类型 | None |
整型 | 0 |
浮点型 | 0.0 |
空字符串 | ‘’ |
空列表 | [] |
空元组 | () |
空字典 | {} |
空集合 | set() |
循环外使用else
如果while或for正常结束,没有遇到break,则会进入到else段内。
使用zip()并行迭代
通过zip()函数对多个序列进行并行迭代:
days = [1,2,3,4,5,6,7]
things = ['sleep', 'lll', '233', 'eat', 'kkk']
years = [2000, 2001, 2002, 2003]
for day,thing,year in zip(days, things, years):
print("In the" + str(day) + "day" + str(year) + "year"+ ",I " + thing)
In the1day2000year,I sleep
In the2day2001year,I lll
In the3day2002year,I 233
In the4day2003year,I eat
函数的返回值既不是元组也不是列表,而是一个整合在一起的可迭代变量。
推导式
列表推导式:
[ expression for item in iterable ]
字典推导式:
[ key_expression : value_expression for expression in iterable ]
集合推导式:
{ expression for expression in iterable }
使用*和**收集参数
(*)将一组可便数量的位置参数集合成参数值的元组
def hhh(*args):
print("name: \tage: ",args)
hhh("gg", 19)
name: age: (‘gg’, 19)
(**)可以将参数收集到一个字典中,参数名称是键,参数的值是键的值。
生成器
用来创建一个python序列对象
def zimu(first = 1, last = 26, step = 1):
maps = {}
c = 'a'
while first <= last:
maps[first] = c
first += step
c = chr(ord(c) + step)
yield maps
maps = list(zimu())[0]
print(maps)
装饰器
实质上是一个把函数作为参数,返回函数的函数
不改变源码的情况下修改已存在的函数
def add_word(func):
def inthe():
print("abc")
func()
return inthe
@add_word
def print_f():
print("ooo")
return
print(print_f())
abc
ooo
None
命名空间和作用域
python提供了两个获取命名空间内容的函数:
locals()返回一个局部命名空间内容的字典
globals()返回一个全部命名空间内容的字典
名称中的_和__的用法
以两个下划线开头和结束的名称都是python的保留用法
如:
函数名称:function.name
函数文档字符串:function.doc