对数字序列运行“for”循环,但我只是使用范围函数重印

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

在线课程提出了这个问题,我无法弄清楚。它应该输出的内容在底部。

def odd_numbers(maximum):

    return_string = "" # Initializes variable as a string

    # Complete the for loop with a range that includes all
    # odd numbers up to and including the "maximum" value.
    for :

        # Complete the body of the loop by appending the odd number
        # followed by a space to the "return_string" variable.


    # This .strip command will remove the final " " space
    # at the end of the "return_string".
    return return_string.strip()
print(odd_numbers(6))  # Should be 1 3 5
print(odd_numbers(10)) # Should be 1 3 5 7 9
print(odd_numbers(1))  # Should be 1
print(odd_numbers(3))  # Should be 1 3
print(odd_numbers(0))  # No numbers displayed

我试过这个:

def odd_numbers(maximum):

    return_string = "" # Initializes variable as a string

    # Complete the for loop with a range that includes all
    # odd numbers up to and including the "maximum" value.
      for n in range(maximum):
            return range(1, n, 2)
        # Complete the body of the loop by appending the odd number
        # followed by a space to the "return_string" variable.
        return_string = ", "

    # This .strip command will remove the final " " space
    # at the end of the "return_string".
    return return_string.strip()
print(odd_numbers(6))  # Should be 1 3 5
print(odd_numbers(10)) # Should be 1 3 5 7 9
print(odd_numbers(1))  # Should be 1
print(odd_numbers(3))  # Should be 1 3
print(odd_numbers(0))  # No numbers displayed

打印出这个:

range(1, 0, 2)
range(1, 0, 2)
range(1, 0, 2)
range(1, 0, 2)

当我使用列表函数时它可以工作,但这不是它应该采用的形式,因为我总是弄错。

python for-loop variables range
1个回答
0
投票

您总是在第一次循环迭代时无条件返回。

您想在每次迭代时附加到

return_string

   for n in range(maximum): 
       return_string += f"{n} "

但是您只想在数字为奇数时才这样做,并且您需要将范围设为

maximum
加一,因为
range
是尾部排除范围。

   for n in range(maximum + 1): 
       if n % 2 == 1:
            return_string += f"{n} "

但是正如您对

range
的使用表明您可能怀疑的那样,这可以更简单。

   for n in range(1, maximum + 1, 2): 
       if n % 2 == 1:
            return_string += f"{n} "

您甚至可能:

    return " ".join(str(n) for n in range(1, maximum + 1, 2))
© www.soinside.com 2019 - 2024. All rights reserved.