python: 流程控制
Posted xinet
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python: 流程控制相关的知识,希望对你有一定的参考价值。
比较、相等和真值
==
操作符测试值的相等性。is
表达式测试对象的一致性。
S1 = ‘spam‘
S2 = ‘spam‘
S1 == S2, S1 is S2
(True, True)
L1 = [1, (‘a‘, 3)] # Same value, unique objects
L2 = [1, (‘a‘, 3)]
L1 == L2, L1 is L2, L1 < L2, L1 > L2
(True, False, False, False)
bool(‘‘)
False
2 and 4
4
2 or 4
2
Python 语句就是告诉你的程序应该做什么的句子。
- 程序由模块构成。
- 模块包含语句。
- 语句包含表达式。
- 表达式建立并处理对象。
真值测试
- All objects have an inherent Boolean true or false value.
- Any nonzero number or nonempty object is true.
- Zero numbers, empty objects, and the special object
None
are considered false. - Comparisons and equality tests are applied recursively to data structures.
- Comparisons and equality tests return
True
orFalse
(custom versions of1
and0
). - Boolean
and
andor
operators return a true or false operand object. - Boolean operators stop evaluating (“short circuit”) as soon as a result is known
真值判定 | 结果 |
---|---|
X and Y |
Is true if both X and Y are true |
X or Y |
Is true if either X or Y is true |
not X |
Is true if X is false (the expression returns True or False ) |
短路计算
or
: 从左到右求算操作对象,然后返回第一个为真的操作对象。and
: 从左到右求算操作对象,然后返回第一个为假的操作对象。
2 or 3, 3 or 2
(2, 3)
[] or 3
3
[] or {}
{}
2 and 3, 3 and 2
(3, 2)
[] and {}
[]
3 and []
[]
断言(assert)
num = -1
assert num > 0, ‘num should be positive!‘
---------------------------------------------------------------------------
AssertionError Traceback (most recent call last)
<ipython-input-13-68d5a766c1dc> in <module>()
1 num = -1
----> 2 assert num > 0, ‘num should be positive!‘
AssertionError: num should be positive!
num = 5
assert num > 0, ‘num should be positive!‘
if 条件
year = int(input(‘请输入年份:‘))
if year % 4 == 0:
if year % 400 == 0:
print(‘闰年‘)
elif year % 100 == 0:
print(‘平年‘)
else:
print(‘闰年‘)
else:
print(‘平年‘)
请输入年份:1990
平年
使用 and
与 or
的短路逻辑:
year = int(input(‘请输入年份:‘))
if (year % 4 == 0 and year % 100 != 0) or year % 400 == 0:
print(‘闰年‘)
else:
print(‘平年‘)
请输入年份:1990
平年
if
的短路(short-ciecuit)计算:A = Y if X else Z
year = int(input(‘请输入年份:‘))
print(‘闰年‘) if (year % 4 == 0 and year % 100 != 0) or year % 400 == 0 else print(‘平年‘)
请输入年份:1990
平年
‘t‘ if ‘spam‘ else ‘f‘
‘t‘
A = [Z, Y][bol(X)]
从列表中挑选真假值 (不推荐使用):
[‘f‘, ‘t‘][bool(‘‘)]
‘f‘
[‘f‘, ‘t‘][bool(‘spam‘)]
‘t‘
a = ‘w‘ ‘d‘ ‘de‘
a
‘wdde‘
while 循环
通用循环结构:
while test: # Loop test
statements # Loop body
else: # Optional else 只有当循环正常离开时才会执行 (也就是没有碰到 `break` 语句)
statements # Run if didn‘t exit loop with break,
continue
:跳到最近所在循环的开头处 (来到循环的首行)break
:跳出最近所在的循环 (跳过整个循环语句)pass
或...
:空占位语句
x = ‘spam‘
while x:
print(x, end=‘ ‘)
x = x[1:]
spam pam am m
X = ...
X
Ellipsis
x = 1 # 初值条件
while x <= 100: # 终止条件
print(x)
x += 27
1
28
55
82
# 拉兹猜想
num = int(eval(input(‘请输入初始值:‘)))
while num != 1:
if num % 2 == 0:
num /= 2
else:
num = num*3+1
print(num)
请输入初始值:5
16
8.0
4.0
2.0
1.0
x = 10
while x:
x -= 1
if x % 2 != 0:
continue # 跳过打印
print(x, end=‘ ‘)
8 6 4 2 0
while True:
name = input(‘Enter name: ‘)
if name == ‘stop‘: break
age = input(‘Enter age: ‘)
print(‘Hello ‘, name, ‘=>‘, int(age)**2)
Enter name: H
Enter age: 25
Hello H => 625
Enter name: stop
和循环 else
子句结合,break
语句通常可以忽略其他语言中所需要的搜索状态标志位。
y = int(input(‘输入数字:‘))
x = y // 2
while x > 1:
if y % x == 0:
print(y, ‘有因子‘, x)
break
x -= 1
else: # 没有碰到 break 才会执行
print(y, ‘是质数!‘)
输入数字:6
6 有因子 3
循环 else
分句是 Python 特有的,它提供了常见的编写代码的明确语法:这是编写代码的结构,让你捕捉循环的“另一条”出路,而不通过设定和检查标志位或条件。
例如,假设你要写一个循环搜索列表的值,而且需要知道在离开循环后该值是否已经找到,可能会用下面的方式编写该任务:
found = False
while x and not found:
if match(x[0]):
print(‘Ni‘)
found = True
else:
x = x[1:]
if not found:
print(‘not found‘)
我们亦可使用循环 else
分句来简化上述代码:
while x:
if match(x[0]):
print(‘Ni‘)
break
x = x[1:]
else:
print(‘not found‘)
for 循环
遍历序列对象:
for target in object: # Assign object items to target
statements # Repeated loop body: use target
else: # Optional else part
statements # If we didn‘t hit a ‘break‘
for i in range(5):
... # 等价于 pass
nums=[1,2,3,4,5]
for i in nums:
print(i)
1
2
3
4
5
list(range(1,10,6))
[1, 7]
# 阶乘
x=1
for i in range(1,11):
x*=i
print(‘10!=‘,x)
10!= 3628800
b = [[9, 7, 3, 6, 5], [10, 2, 4, 6, 7], [0, 5, 3, 2, 9], [7, 3, 5, 6, 1]]
s = 0
for i in range(len(b)):
for j in range(len(b[i])):
s += b[i][j]
print(s)
100
for x in range(1, 10):
for y in range(1, x + 1):
print(end=‘|‘)
print(‘%d*%d=%2d‘ % (x, y, x * y), end=‘|‘)
print()
|1*1= 1|
|2*1= 2||2*2= 4|
|3*1= 3||3*2= 6||3*3= 9|
|4*1= 4||4*2= 8||4*3=12||4*4=16|
|5*1= 5||5*2=10||5*3=15||5*4=20||5*5=25|
|6*1= 6||6*2=12||6*3=18||6*4=24||6*5=30||6*6=36|
|7*1= 7||7*2=14||7*3=21||7*4=28||7*5=35||7*6=42||7*7=49|
|8*1= 8||8*2=16||8*3=24||8*4=32||8*5=40||8*6=48||8*7=56||8*8=64|
|9*1= 9||9*2=18||9*3=27||9*4=36||9*5=45||9*6=54||9*7=63||9*8=72||9*9=81|
d = {‘k1‘: 1, ‘k2‘: 2, ‘k3‘: 3}
for i in d:
print(i, ‘:‘, d[i])
k1 : 1
k2 : 2
k3 : 3
d = {‘k1‘: 1, ‘k2‘: 2, ‘k3‘: 3}
for key, value in d.items():
print(key, ‘:‘, value)
k1 : 1
k2 : 2
k3 : 3
a, *b, c = 1, 2, 3, 4, 5
a, b, c
(1, [2, 3, 4], 5)
以上是关于python: 流程控制的主要内容,如果未能解决你的问题,请参考以下文章
VSCode自定义代码片段15——git命令操作一个完整流程