Python 嵌套循环 _ 需要帮助

问题描述 投票:0回答:2

我无法理解这一点。我刚开始学习python,对循环感到困惑

def sequence(low, high):
    # Complete the outer loop range to make the loop run twice
    # to create two rows
    for x in range(___): 
        # Complete the inner loop range to print the given variable
        # numbers starting from "high" to "low" 
        # Hint: To decrement a range parameter, use negative numbers
        for y in range(___): 
            if y == low:
                # Don’t print a comma after the last item
                print(str(y)) 
            else:
                # Print a comma and a space between numbers
                print(str(y), end=", ") 

下面应该打印序列3,2,1两次,如上所示。

sequence(1, 3)

这应该打印序列 3, 2, 1 两次,如上所示。

sequence(1, 3)

无法理解范围内的内容以及嵌套循环的功能

python nested-loops
2个回答
0
投票

你要找的代码是这个。我会在代码注释中解释原因。

def sequence(low, high):
    # range works by putting the number of times you want it to run inside of it
    for x in range(2):
        # (argument1, argument 2, step) this means, Go from high, to low. low-1 is used because range will include everything up to the last argument, so including a -1 will allow you to include the last item. The -1 means go down by 1 each time.
        for y in range(high, low-1, -1):
            if y == low:
                # y == low will check that the y in the range is the lowest, if its not then it will run again. Once it is the lowest, it will print the string. The range by the way is defined by the sequence(1,3) we put at the end. If you change the numbers, it will change the range.
                print(str(y))
            else:
                # Print a comma and a space between numbers
                print(str(y), end=", ")
sequence(1,3)

0
投票

嵌套循环只是其他循环中的循环。在这种情况下,您有一个外循环负责要打印的行数,还有一个内循环负责打印每行中的数字序列。

对于您的代码,您想打印从

high
low
的序列两次。以下是更新后的代码:

def sequence(low, high):
    # Complete the outer loop range to make the loop run twice
    # to create two rows
    for x in range(2):  # Loop will run two times, creating two rows
        # Complete the inner loop range to print the given variable
        # numbers starting from "high" to "low"
        # Hint: To decrement a range parameter, use negative numbers
        for y in range(high, low-1, -1):  # Loop will run from "high" to "low" with a step of -1
            if y == low:
                # Don’t print a comma after the last item
                print(str(y))
            else:
                # Print a comma and a space between numbers
                print(str(y), end=", ")

# Call the function to test it
sequence(1, 3)

输出:

3, 2, 1
3, 2, 1

这是代码的作用:

  1. 外循环
    for x in range(2)
    会运行两次,因为范围设置为
    2
    。这将创建两行序列。
  2. 内循环
    for y in range(high, low-1, -1)
    将从
    high
    low
    (含),步长为
    -1
    。这意味着循环将从
    high
    开始并递减
    1
    直到它到达
    low
    .
  3. 内部循环将打印数字以及逗号和空格,但最后一个数字(
    low
    )除外。最后一个数字将在没有逗号的情况下打印。

当你调用函数

sequence(1, 3)
时,它会打印序列
3, 2, 1
两次,就像你想要的那样。

© www.soinside.com 2019 - 2024. All rights reserved.