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.")
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 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)
将列表中元素的index和value一起进行迭代
animals = ["dog", "cat", "mouse"]
for i, value in enumerate(animals):
print(i, value)
# 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