ten_things = "Apples Oranges Crows Telephone Light Sugar"
print("Wait there are not 10 things in that list. Let's fix that.")
stuff = ten_things.split(' ')
more_stuff = ["Day", "Night", "Song", "Frisbee",
"Corn", "Banana", "Girl", "Boy"]
while len(stuff) != 10:
next_one = more_stuff.pop() # pop
print("Adding:", next_one)
stuff.append(next_one)
print(f"There are {len(stuff)} items now.")
print("There we go:", stuff)
print("Let's do some things with stuff.")
print(stuff[1])
print(stuff[-1]) # whoa! fancy
print(stuff.pop())
print(' '.join(stuff)) # what? cool!
print('#'.join(stuff[3:5])) # super stellar!
运行错误:more_stuff中的元素无法被添加到stuff中,每循环一次,就有一个新元素被添加到stuff尾端,但上一次循环添加的元素消失,stuff总数始终为7,最终当pop()函数使得more_stuff中的元素减少至0时循环结束。
错误原因:15行:print("There we go:", sutff)从此行开始应该结束缩进,即以下代码块不属于while循环的内容
错误逻辑分析:当使用此错误缩进时,我们输出的始终是一次循环中的内容,而一次循环中包含第21行:stuff.pop( )函数,则把本次循环加入stuff尾部的元素删除,故stuff总数始终为7.
修改方法:只需要保证21行:stuff.pop( ) 函数在while循环外即可
得到教训:通过缩进可以将代码分块,务必重视分块后的各项功能,不能随意缩进!!
正确代码如下
ten_things = "Apples Oranges Crows Telephone Light Sugar"
print("Wait there are not 10 things in that list. Let's fix that.")
stuff = ten_things.split(' ') # 表示以空格为分隔符
more_stuff = ["Day", "Night", "Song", "Frisbee",
"Corn", "Banana", "Girl", "Boy"]
while len(stuff) != 10:
next_one = more_stuff.pop() # pop()函数用于移除列表中最后一个元素,并返回该元素的值
print("Adding:", next_one)
stuff.append(next_one) # 将next_one加到stuff尾部
print(f"There are {len(stuff)} items now.")
print("There we go:", stuff)
print("Let's do some things with stuff.")
print(stuff[1])
print(stuff[-1]) # -1号元素即最后一个元素
print(stuff.pop()) # 此处删除stuff最后一个元素,并返回其值打印出来
print(' '.join(stuff)) # 用空格将stuff列表连接起来
print('#'.join(stuff[3:5])) # 用#将stuff中3、4号元素连接起来