if else语句

if some_var > 10:
    print("some_var is totally bigger than 10.")
elif some_var < 10:    # This elif clause is optional.
    print("some_var is smaller than 10.")
else:                  # This is optional too.
    print("some_var is indeed 10.")

Match/Case语句

command = "run"

match command:
    case "run":
        print("The robot started to run 🏃‍♂️")
    case "speak" | "say_hi":  # multiple options (OR pattern)
        print("The robot said hi 🗣️")
    case code if command.isdigit():  # conditional
        print(f"The robot execute code: {code}")
    case _:  # _ is a wildcard that never fails (like default/else)
        print("Invalid command ❌")

for循环语句

  • 循环语句需要迭代器,迭代器可以是列表,也可以使用range()函数生成顺序数字组成的列表。
for animal in ["dog", "cat", "mouse"]:
    # You can use format() to interpolate formatted strings
    print("{} is a mammal".format(animal))

for i in range(4):
    print(i)
for i in range(4, 8):
    print(i)
for i in range(4, 8):
    print(i)
  • 将列表中元素的indexvalue一起进行迭代
animals = ["dog", "cat", "mouse"]
for i, value in enumerate(animals):
    print(i, value)

while循环语句

x = 0
while x < 4:
    print(x)
    x += 1  # Shorthand for x = x + 1

可迭代iterable对象

filled_dict = {"one": 1, "two": 2, "three": 3}
our_iterable = filled_dict.keys()

注意可迭代对象不能通过Index取值

our_iterable[1]  # Raises a TypeError

可迭代对象可以用来构造迭代器iter()函数

our_iterator = iter(our_iterable)

迭代器的next()函数可以获取下一个元素

print(next(our_iterator))  # "one"

StopIteration异常:当迭代器已将迭代完后再对其进行迭代

注意区分可迭代对象和由iter()生成的迭代器

# You can grab all the elements of an iterable or iterator by call of list().
list(our_iterable)  # => Returns ["one", "two", "three"]
list(our_iterator)  # => Returns [] because state is saved