cars = ['bmw', 'audi', 'toyota', 'subaru'] print("Here is the original list:") print(cars) print("\nHere is the sorted list:") print(sorted(cars)) print("\nHere is the original list again:") print(cars)
magicians = ['alice', 'david', 'carolina'] for magician in magicians: print(magician,end=',')
使用单数或复数这些命名约定可以帮助判断代码处理的是单个列表元素还是整个列表
1 2 3
for cat in cats: for dog in dogs: for item in list_of_items:
在 for 循环中执行更多的操作
1 2 3 4
magicians = ['alice', 'david', 'carolina'] # 在代码行for magician in magicians后面,每个缩进的代码行都是循环的一部分,且将针对列表中的每个值都执行一次 for magician in magicians: print(magician.title() + ", that was a great trick") print("I can't wait to see your next trick" + magician.title() + ".\n")
在 for 循环结束后执行一些操作
1 2 3 4 5
magicians = ['alice', 'david', 'carolina'] for magician in magicians: print(magician.title() + ", that was a great trick") print("I can't wait to see your next trick" + magician.title() + ".\n") print("Thank you, everyone. That was a great magic show!") # 在循环外打印
忘记缩进 python将提示 IndentationError: expected an indented block
1 2 3
magicians = ['alice', 'david', 'carolina'] for magician in magicians: print(magician)
忘记缩进额外的代码行
1 2 3 4 5 6 7 8 9 10 11 12
# 有时候循环可能会正常运行但结果可能会出乎意料 # 试图在循环中执行多项任务,却忘记缩进其中的一些代码行时,就会出现这种情况 # 示例源码 magicians = ['alice', 'david', 'carolina'] for magician in magicians: print(magician.title() + ", that was a great trick!") print("I can't wait to see your next trick, " + magician.title() + ".\n")
print("Thank you everyone, that was a great magic show!") # 第九行忘记缩进 # 因第一行缩进所以未报错 没有未进入循环 所以只打印了一位魔术师 # 总结如果想自己的代码依次执行循环请缩进到for循环语句块内 # 这也是一个逻辑错误