简体   繁体   English

在产生一定数量后如何打破循环?

[英]How to break a loop after it yields a certain number?

So here is my code, I have created this program so that it will run in a loop until either DIGITS 1 and 4 occur in the output, which will then break, but I want to change it in a way so that instead of "break" after either digits 1 or 4 are detected, I want it to break only after the output yields 1 or 4, how can I do that??所以这是我的代码,我已经创建了这个程序,以便它会在循环中运行,直到输出中出现 DIGITS 1 和 4,然后会中断,但我想以某种方式更改它,而不是“中断" 在检测到数字 1 或 4 后,我希望它仅在输出产生 1 或 4 后中断,我该怎么做? Here is my code..这是我的代码..

what should I do to make sure it stops when the output itself, not the DIGITS in the output, the output itself, yields either 1 or 4?当输出本身,而不是输出中的 DIGITS,输出本身产生 1 或 4 时,我应该怎么做才能确保它停止?

You can just loop over and over and check the entire sum_of_digits .您可以一遍又一遍地循环并检查整个sum_of_digits Try this:尝试这个:

number = 145
sum_of_digits = 0
x = ''
while x not in ['1', '4']:
    for digit in str(number):
       sum_of_digits += (int(digit)**2)
    x = str(sum_of_digits)
    number = sum_of_digits
    sum_of_digits = 0
print(x)

my output: 4我的输出:4

This can be improved but I didn't want to change much more of your code这可以改进,但我不想更改更多代码

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM