为什么不“休息"?停止此循环? [英] Why doesn't "break" stop this for loop?

查看:64
本文介绍了为什么不“休息"?停止此循环?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

for i in range(999*999):
    if ispalindrome(999*999-i)==True and isprime(999*999-i) == False:
        factors = listfactors(999*999-i)
        for j in range(len(factors)):
            if len(str(factors[j])) == 3 and len(str(int((999*999-i)/factors[j])))==3:
                print(999*999-i)
                quit()

这是我的代码.我想检查这些条件是否成立,然后在找到第一个条件后立即停止,但是它将在控制台中显示所有符合条件的数字.我的想法是,当它有第一个数字时,它应该停止

This is my code. I want to check whether these conditions are true and then stop once I've found the first one, but it prints all of the numbers that fit the conditions in the console. My thinking was that it should stop when it's got the first number

我尝试使用quit()而不是break,但这仍然行不通,这是我不理解的.我确实用两个break语句尝试过,但这没用.我想知道缩进是否正确.

I tried using quit() instead of break, but this still doesn't work, which I don't understand. I did try it with two break statements, but that didn't work. I wonder whether I got the indentation wrong.

推荐答案

要退出双循环,请改用一个函数,然后从该函数返回.中断仅适用于最内层的循环.

In order to quit a double loop, use a function instead and return from the function. A break only works for the innermost loop.

示例:

def whatever():
    for i in range(999 * 999):
        if ispalindrome(999 * 999 - i) and not isprime(999 * 999 - i):
            factors = listfactors(999 * 999 - i)
            for j in factors:
                if len(str(j)) == 3 and len(str(int((999 * 999 - i) / j))) == 3:
                    return 999*999-i

print(whatever())

这篇关于为什么不“休息"?停止此循环?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆