0%

Mosh的Python课程笔记(3)--Control Flow

Mosh的课程网址

Comparison Operators

1
2
3
4
5
6
7
8
9
10
11
12
>>> 10 > 3
True
>>> 10 >= 3
True
>>> 10 < 20
True
>>> 10 == 10
True
>>> 10 == "10"
False
>>> 10 != "10"
True
1
2
3
4
5
6
7
8
>>> "bag" > "apple" 
True
>>> "bag" == "BAG"
False
>>> ord("b")
98
>>> ord("B")
66

Chaining Comparison Operators

1
2
3
4
# age should be between 18 and 65
age = 22
if 18 <= age < 65:
print("Eligible")

Conditional Statements

1
2
3
4
5
6
7
8
9
10
11
12
temperature = 15
if temperature > 30:
print("It is warm")
print("Drink water")

elif temperature > 20:
print("It's nice")

else:
print("It's cold")

print("Done")

Ternary Operator

1
2
3
4
5
6
7
8
9
10
age = 2

# if age >= 18:
# message = "Eligible"
# else:
# message = "Not eligible"

message = "Eligible" if age >= 18 else "Not eligible"

print(message)

Logical Operators

1
2
3
4
5
6
7
8
9
10
# logical operators: and, or, not

high_income = True
good_credit = False
student = False

if (high_income or good_credit) and not student:
print("Eligible")
else:
print("Not eligible")

Short-circuit Evaluation

多条件判断时:

and 前面的 expression 为 False, 则不再(执行)判断后面的expression

or 前面的 expression 为 True, 则不再(执行)判断后面的expression

For Loops

1
2
for number in range(1, 10, 2):		# step: 2
print("Attempt", number, number * ".")

输出:

1
2
3
4
5
Attempt 1 .
Attempt 3 ...
Attempt 5 .....
Attempt 7 .......
Attempt 9 .........

For…Else

1
2
3
4
5
6
7
8
successful = False
for number in range(3):
print("Attempt")
if successful:
print("Successful")
break
else:
print("Attempted 3 times and failed.")

如果一直没有执行break,就执行下面的else

输出结果:

1
2
3
4
Attempt
Attempt
Attempt
Attempted 3 times and failed

Nested Loops

1
2
3
for x in range(5):
for y in range(3):
print(f"({x}, {y})")

输出结果

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
(0, 0)
(0, 1)
(0, 2)
(1, 0)
(1, 1)
(1, 2)
(2, 0)
(2, 1)
(2, 2)
(3, 0)
(3, 1)
(3, 2)
(4, 0)
(4, 1)
(4, 2)

Iterables

1
2
3
4
5
6
# Iterable : range(), string, list...
for x in "Python":
print(x)

for x in [1, 2, 3, 4]:
print(x)

输出:

1
2
3
4
5
6
7
8
9
10
P
y
t
h
o
n
1
2
3
4

While Loops

1
2
3
4
command = ""
while command.lower() != "quit":
command = input(">")
print("ECHO", command)

输出结果:

1
2
3
4
5
6
>2+2
ECHO 2+2
>3*4
ECHO 3*4
>quit
ECHO quit

Infinite Loops

1
2
3
4
5
while True:
command = input(">")
print("ECHO", command)
if command.lower() == "quit":
break

Exercise

编写一段code,输出1~10之间(不含10)的偶数,如下:

1
2
3
4
5
2
4
6
8
We have 4 even numbers