
Conditional statements (if, elif, else) in Python 3.
1 2 3 4 5 6
|
x = 5 if x < 10: print('Smaller') if x > 20: print ('Larger') print('Finish')
|
用缩进,不是花括号
1 2 3 4 5 6 7 8 9 10 11
|
if x > 2: print('Bigger than 2') print('Still bigger') print('Done with 2')
for i in range(5): print(i) if i > 3: print('Bigger than 3') print('Done with i', i); print('All done')
|
Nested If
1 2 3 4 5 6
|
y = 42 if y > 1: print('Y is larger than 1') if y < 100: print('Y is smaller than 100') print('All done')
|
if-else
1 2 3 4 5
|
y = 100 if y == 100: print('Y is 100') else: print('Y is not 100')
|
Multi-way (“elif” which is “else if”)
1 2 3 4 5 6
|
if y > 100: print('Y is larger than 100') elif y == 100: print('Y is 100') else: print('Y is smaller than 100')
|
try-except (catch errors)
1 2 3 4 5 6 7 8 9 10 11 12 13
|
str1 = 'Hello' try: num1 = int(str1) except: num1 = -1 print('first string-', num1)
str2 = '123' try: num1 = int(str2) except: num1 = -1 print('second string-', num1)
|

图中1正常,2出错,到3,4是不会运行的。所以在try里面写过多逻辑是不合理的,尽量简单。
近期评论