笨办法学python3——习题38

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号元素连接起来

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值