布尔条件
用作布尔表达式时,下面的值都将被解释器视为假:False None 0 "" () [] {}
True和False不过是0和1的别名,虽然看起来不同,但作用是相同的。
比较运算符 | |
表达式 | 描 述 |
x == y | x 等于y |
x < y | x小于y |
x > y | x大于y |
x >= y | x大于或等于y |
x <= y | x小于或等于y |
x != y | x不等于y |
x is y | x和y是同一个对象 |
x is not y | x和y是不同的对象 |
x in y | x是容器(如序列)y的成员 |
x not in y | x不是容器(如序列)y的成员 |
字符串和序列的比较
print('e:{}'.format(ord('e')))
print('F:{}'.format(ord('F')))
print('f:{}'.format(ord('f')))
# output: e:101
# output: F:70
# output: f:102
print('efg' > 'fgh')
# output: False
print('efg' > 'egh')
# output: False
print('efg' > 'd')
# output: True
print('efg' > 'Fgh')
# output: True
if、else、elif
# if boolCondition:
# action
if 2>1:
print(True)
if 2 < 1:
print(False)
# output: True
# if boolCondition:
# action1
# else:
# action2
a = 2
if a > 1:
print('a={0}:True'.format(a))
else:
print('a={0}:False'.format(a))
# output: a=2:True
# output: a=1:False
a = 5 # (2\4\5)
if a == 1:
print('a={0}:action1'.format(a))
elif a == 2:
print('a={0}:action2'.format(a))
elif a == 3:
print('a={0}:action3'.format(a))
elif a == 4:
print('a={0}:action4'.format(a))
else:
print('a={0}:action5'.format(a))
# output: a=2:action2
# output: a=4:action4
# output: a=5:action5
链式比较
a = 2 # (2\5)
if 1 < a < 4:
print('a={0}:action1'.format(a))
else:
print('a={0}:action2'.format(a))
# output: a=2:action1
# output: a=5:action2
断言assert
在程序中添加assert语句充当检查点。
assert 语句是在程序中插入调试性断言的简便方式:
assert_stmt ::= "assert" expression ["," expression]
简单形式 assert expression
等价于
if __debug__:
if not expression: raise AssertionError
扩展形式 assert expression1, expression2
等价于
if __debug__:
if not expression1: raise AssertionError(expression2)
a = -1
assert a > 0
# output: Traceback (most recent call last):
# File "E:\PyCode\Python_Study\LsitDemo.py", line 2, in <module>
# assert a > 0
# AssertionError
assert a > 0, 'a为负数'
# output: Traceback (most recent call last):
# File "E:\PyCode\Python_Study\LsitDemo.py", line 7, in <module>
# assert a > 0, 'a为负数'
# AssertionError: a为负数
While循环
# while condition:
# action
a = 0
while a < 10:
a += 1
print(a)
# output: 10
# while condition:
# action with break
a = 2 # (-2,2)
while a < 10:
if a < 0:
print('into break')
break
else:
a += 1
else:
print('into else')
print(a)
# output: into break
# output: -2
# output: into else
# output: 10
# while condition:
# action with continue
# else:
# action
a = -2
while a < 10:
if a < 0:
a += 1
print('into continue')
continue
else:
a += 100
else:
print('into else')
print(a)
# output: into continue
# output: into continue
# output: into else
# output: 100
For循环
只要能够使用for循环,就不要使用while循环。
for num in list(range(5)):
print(num)
# output: 0
# output: 1
# output: 2
# output: 3
# output: 4
for num1 in list(range(5)):
if num1 not in [x for x in list(range(1,4))]:
print(num1)
# output: 0
# output: 4
迭代字典
dict1 = {'name': 'python', 'vision': '310'}
for k in dict1:
print('{0}:{1}'.format(k, dict1[k]))
# output: name:python
# output: vision:310
并行迭代
names = ['pin', 'coco', 'jeff']
heights = [148, 123, 168]
for k in range(len(names)):
print('name:{0},height:{1}'.format(names[k], heights[k]))
# output: name:pin,height:148
# output: name:coco,height:123
# output: name:jeff,height:168
for name, height in zip(names, heights):
print('name:{0},height:{1}'.format(name, height))
# output: name:pin,height:148
# output: name:coco,height:123
# output: name:jeff,height:168
print(list(zip(zip(names, heights))))
# output: [(('pin', 148),), (('coco', 123),), (('jeff', 168),)]
strings = 'python'
heights = [148, 123, 168]
for i, j in enumerate(strings):
print('name:{0},height:{1}'.format(i, j))
# output: name:0,height:p
# output: name:1,height:y
# output: name:2,height:t
# output: name:3,height:h
# output: name:4,height:o
# output: name:5,height:n
顺序迭代和反向迭代
list1 = [1, 3, 2]
for i in sorted(list1):
print(i)
# output: 1
# output: 2
# output: 3
for i in sorted(list1, reverse=True):
print(i)
# output: 3
# output: 2
# output: 1
list2 = list('bca')
for i in sorted(list2, key=str.upper):
print(i)
# output: a
# output: b
# output: c
推导
使用圆括号代替方括号并不能实现元组推导,而是将创建生成器。可使用花括号来执行字典推导。
print([x for x in range(10)])
# output: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
print([x ** 2 for x in range(10) if x < 5])
# output: [0, 1, 4, 9, 16]
print([(x, y) for x in range(0, 3) for y in range(4, 7)])
# output: [(0, 4), (0, 5), (0, 6), (1, 4), (1, 5), (1, 6), (2, 4), (2, 5), (2, 6)]
dict1 = {'{0}:{1}'.format(i, i ** 2) for i in range(3)}
print(dict1)
# output: {'2:4', '0:0', '1:1'}
match
匹配语句用于进行模式匹配。语法如下
match_stmt ::= 'match' subject_expr ":" NEWLINE INDENT case_block+ DEDENT
subject_expr ::= star_named_expression "," star_named_expressions?
| named_expression
case_block ::= 'case' patterns [guard] ":" block
模式匹配接受一个模式作为输入(跟在 case
后),一个主词值(跟在 match
后)。该模式(可能包含子模式)与主题值进行匹配。输出是:
-
匹配成功或失败(也被称为模式成功或失败)。
-
可能将匹配的值绑定到一个名字上。 这方面的先决条件将在下面进一步讨论。
单匹配(匹配特定值)
while 1:
inputNum = int(input("please input a number 1:5\n"))
match inputNum:
case 1:
print('the number is 1')
case 2:
print('the number is 2')
case 3:
print('the number is 3')
case 4:
print('the number is 4')
case 5:
print('the number is 5')
# input: 1
# output: the number is 1
# input: 4
# output: the number is 4
command = input("What are you doing next? ")
match command.split():
case ["quit"]:
print("quit game")
case ["pause"]:
print("pause game")
case ["kill", obj]: # kill player
print("kill the", str(obj))
case ["go", direction]:
print("go ", str(direction))
# input: quit
# output: quit game
# input: kill player1
# output: kill the player1
# input: go east
# output: go east
或模式
while 1:
inputNum = int(input("please input a number 1:5\n"))
match inputNum:
case 1 | 2 | 3 | 4 | 5:
print('the number is between 1 and 5')
# input: 1
# output: the number is between 1 and 5
# input: 4
# output: the number is between 1 and 5
匹配多个值
command = input("What are you doing next? ")
match command.split():
case ["kill", *objs]: # kill players
for obj in objs:
print('kill the ', obj)
# input: kill player1 player2 player3 player4
# output: kill the player1
# output: kill the player2
# output: kill the player3
# output: kill the player4
通配符
这种写入_
(并称为通配符)的特殊模式始终匹配,但它不绑定任何变量。
请注意,这将匹配任何对象,而不仅仅是序列。
command = input("What are you doing next? ")
match command.split():
case ["quit"]:
print("quit game")
case ["kill", obj]: # kill player
print("kill the", str(obj))
case _:
print("do nothing")
# input: quit
# output: quit game
# input: kill player1
# output: kill the player1
# input: go east
# output: do nothing
匹配的子模式
command = input("What are you doing next? ")
match command.split():
case ["quit"]:
print("quit game")
case ["go", ("north" | "south" | "east" | "west") as direction]:
print("go ", str(direction))
case _:
print("do nothing")
# input: quit
# output: quit game
# input: go east
# output: go east
# input: go home
# output: do nothing
像匹配添加条件
command = input("What are you doing next? ")
directionList = ["gop", "south"]
match command.split():
case ["quit"]:
print("quit game")
case ["go", direction] if direction in directionList:
print("go ", str(direction))
case _:
print("do nothing")
# input: quit
# output: quit game
# input: go east
# output: do nothing
# input: go north
# output: go north
这里就不详细介绍了,可以查看官网更多介绍:
PEP 636 – Structural Pattern Matching: Tutorial | peps.python.org