【问题标题】:Converting a for loop into a while loop将 for 循环转换为 while 循环
【发布时间】:2018-02-22 21:03:18
【问题描述】:

我已经完成了一个 for 循环,如果另一个 2 旁边有一个 2,则返回 true,现在我正在尝试使用 while 循环来执行此操作。我似乎无法让我的 while 循环工作。

这是我完成的 for 循环

def has22(nums):
    "Return true if array contains a 2 next to a 2 somewhere"""
    for i in range(0, len(nums)-1):
        if nums[i] == 2 and nums[i+1] == 2:
            return True    
    return False

我尝试运行这个 while 循环,但它不起作用。

def has22(nums):
    """While loop version"""
    i = 0
    while i < len(nums) - 1:
        if nums[i] == 2 and nums[i+1] == 2:
        return True
        i += 1

有人可以告诉我它有什么问题吗?

【问题讨论】:

    标签: python-3.x while-loop


    【解决方案1】:
    1. return True 没有缩进,所以它总是被返回(即它不是if 语句的主体)

    2. 函数从不返回 `False

    试试:

    def has22(nums):
        """While loop version"""
        i = 0
        while i < len(nums) - 1:
            if nums[i] == 2 and nums[i+1] == 2:
                return True
            i += 1
        return False
    

    【讨论】:

    • i += 1 在 while 循环的主体中:您希望它在循环的每次迭代中运行,而不仅仅是在 if 条件为 True 时运行
    猜你喜欢
    • 2017-04-26
    • 2018-08-19
    • 1970-01-01
    • 1970-01-01
    • 2022-12-04
    • 2020-06-20
    • 1970-01-01
    相关资源
    最近更新 更多