python course 1 week 5 用缩进,不是花括号 Nested If if-else Multi-way (“elif” which is “else if”) try-except (catch errors)

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') #still in the block
print('Done with 2') #out of the if

for i in range(5): #loop
print(i)
if i > 3:
print('Bigger than 3')
print('Done with i', i); #out of if
print('All done') #out of the for loop

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) # trackback, error here
except:
num1 = -1 # this return
print('first string-', num1) # output: first string- -1

str2 = '123'
try:
num1 = int(str2) # works
except:
num1 = -1
print('second string-', num1) # output: second string- 123

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