1. 程式人生 > >python: 流程控制

python: 流程控制

range spam 流程控制 通過 ould 代碼 rcu equal should

比較、相等和真值

  • == 操作符測試值的相等性
  • 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 or False (custom versions of 1 and 0).
  • Boolean and and or 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
平年

使用 andor 的短路邏輯:

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: 流程控制