【问题标题】:What happens in this while loop in pythonpython的这个while循环会发生什么
【发布时间】:2020-01-07 00:13:53
【问题描述】:

所以我在 edx 上学习了 Python 的第二门课程,这是我编写的代码,但并不真正理解 while 循环中的部分。有人可以像我 6 岁那样向我解释那里发生了什么吗?

代码:

# [ ] Print each word in the quote on a new line  
quote = "they stumble who run fast"
start = 0
space_index = quote.find(" ")

while space_index != -1:  #the code in while needs to be explained to me 
    print(quote[start:space_index])
    start = space_index +1
    space_index = quote.find(" ", space_index +1)

【问题讨论】:

    标签: python-3.x loops while-loop


    【解决方案1】:

    您的代码尝试演示如何在 Python 中按索引从字符串中检索子字符串,使用具有该索引作为停止条件的 while 循环。

    Python 文档on the function find() of string is here。引用自它:

    步骤如下:

    1. 如何检索字符串quote中给定字符第一次出现的索引。 在这一行:quote.find(" "),它返回第一个位置的索引空格。所以当 while 循环开始时,space_index 将等于 4。

    2. 如何从字符串中检索子字符串。 在这一行中:quote[start:space_index] 如果你翻译变量startspace_index,你得到的是:@ 987654331@ 等于第一次迭代中的“他们”。

    3. 如何增加索引。while 的末尾,您再次执行quote.find(" ", space_index +1) 尝试获取空格 @ 的索引987654334@。但是这次你开始搜索的位置是space_index+1,在第一次迭代中是5。函数quote.find将返回值12。

    4. 所以在 while 的第二次迭代中: 您将尝试获取子字符串 quote[start:space_index] 或替换值:quote[5:12] 这将是第二个词“绊倒”。

    您应该尝试学习如何使用您正在使用的 IDE 的调试器,或者尝试打印所有中间值以便查看它们。

    【讨论】:

      【解决方案2】:

      代码基本上是逐行打印由空格分隔的每个单词。

      评论片段:

      # [ ] Print each word in the quote on a new line  
      quote = "they stumble who run fast"
      start = 0    ## index of first character
      space_index = quote.find(" ")
      
      while space_index != -1:  #the code in while needs to be explained to me 
          print(quote[start:space_index])   ## print characters from start index to space character
          start = space_index +1            ## shift the start index to just after the up-coming space character
          space_index = quote.find(" ", space_index +1)  ## find the index of the next space character
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-10-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-03-29
        • 2021-12-26
        • 1970-01-01
        相关资源
        最近更新 更多