Python——为数字序列运行“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} "
© www.soinside.com 2019 - 2024. All rights reserved.