简体   繁体   English

Python 重新启动循环

[英]Python Restarting a loop

How can I restart the loop in the following code after it hits 1 since in 3N+1 it goes 1>4>2>1?我如何在以下代码中重新启动循环,因为它在 3N+1 中达到 1,因为它在 1>4>2>1 中变为 1?

Code:代码:

import math
import random
num = 1
NumTF = False
play = True
while play:
  if num % 2 == 0:
    num = num / 2
  else:
    num = 3 * num + 1
print(num)
if num == 1:
  play = False
if play == False:
  num += 1 and play == True

I'm assuming that you want to end the loop, because...Collatz Conjecture.我假设你想结束循环,因为......科拉茨猜想。

All you have to do is add this simple if statement to the end:您所要做的就是将这个简单的 if 语句添加到末尾:

elif num == 1:
    play = False

after the if num%2 == 0 statement, so the while loop ends.if num%2 == 0语句之后,所以 while 循环结束。 Currently, your doing this after your doing num = 3*num+1 , which makes it 4, so that case never happens.目前,您在执行num = 3*num+1之后执行此操作,这使其变为 4,因此这种情况永远不会发生。 as rv.kvetch mentioned, the play==True does unexpected things, so just delete everything after print(num) , as those are unnecessary.正如 rv.kvetch 提到的, play==True做了意想不到的事情,所以只需删除print(num)之后的所有内容,因为这些都是不必要的。

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

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