【问题标题】:How to begin a new loop from the end result of a previous loop如何从前一个循环的最终结果开始一个新循环
【发布时间】:2020-01-26 22:20:44
【问题描述】:

我在 Python 中有以下代码:

如果我按原样运行代码,如果我输入数字 9,它将运行从 0 到 8 的数字列表。并且每次我重新运行代码时,它都会自动从 0 开始。附加代码做什么我需要让它从上一个循环的最终结果开始运行(即我从 9 开始,然后当我第二次使用 8 时,它从 8 开始运行循环,因为这是上一个循环的最终结果) ?


while user_play == "y":

    # Ask the user how many numbers to loop through
    ask_user = input("How many numbers would you like to loop? ")


    # Loop through the numbers. (Be sure to cast the string into an integer.)
    for number in range(0,int(ask_user)):

        # Print each number in the range
        print(number)


    # Once complete, ask the user if they would like to continue
    user_play = input("Would you like to continue? ")```

【问题讨论】:

  • 分配一个变量作为range()的开头,然后在每次运行时更新它

标签: python for-loop input while-loop range


【解决方案1】:

不要将 range(0,int(ask_user)) 的开头硬编码为 0,而是使用变量 start 初始化为 0,并在每个循环中使用最后一个值进行更新。

start = 0  # initialize at 0
while user_play == "y":

    # Ask the user how many numbers to loop through
    ask_user = input("How many numbers would you like to loop? ")


    # Loop through the numbers. (Be sure to cast the string into an integer.)
    for number in range(start, start + int(ask_user)): 

        # Print each number in the range
        print(number)
        start = number # update start


    # Once complete, ask the user if they would like to continue
    user_play = input("Would you like to continue? ")```

【讨论】:

    【解决方案2】:

    你很亲密。只需进行两项更改。

    变化

    1) 在 while 循环之外,将 number 的初始值设置为零。

    2) 将范围改为range(number, number+int(ask_user))

    结果

    number = 0
    while user_play == "y":
        ask_user = input("How many numbers would you like to loop? ")
        for number in range(number, number + int(ask_user)):
            print(number)
        user_play = input("Would you like to continue? ")
    

    工作原理

    这个想法是 number 总是意味着“你在循环中的位置”,而 ask_user 表示应该运行多少步。 数字从零开始,随着步数的增加被记住。

    变化

    根据您是否要重复某个步骤,请考虑在数字上加一。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-03-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-04
      • 2021-11-04
      • 2015-11-28
      • 1970-01-01
      相关资源
      最近更新 更多