新手编码器问题正确循环

时间:2017-03-04 01:09:34

标签: python-3.x loops

所以我是一名从未编过代码的新手编码器,并且在我的CS教练指导下自学Python。我正在逐步完成“使用Python自动化无聊的东西”,我在第3章末尾遇到了Collat​​z序列部分的问题。我已经解决了序列,但是我遇到了正确循环代码的问题为了获得我想要的结果,循环序列直到答案是==到整数1.这就是我所拥有的,我会喜欢一些反馈和帮助。

def collatz(number): #defines the collatz sequence
    if number%2 == 0:
        num1 = number//2
    else:
        num1 = 3 * (number + 1)
    return num1

print("Let's try the collatz sequence. Enter a number")
num = int(input())
num3 = collatz(num)
while num3 != 1: #loops collatz sequence until it equals 1
    num2 = collatz(num3)
    if num2 == 1:
        break
    else:
        num3 = collatz(num2)    
print("ta da!")

1 个答案:

答案 0 :(得分:0)

您需要以下代码:

def collatz(number):
    if number % 2 == 0:
        num1 = number//2
    else: num1 = 3 * number + 1 # Do not use brackets!!! Or you will have infinite loop
    return num1

print("Let's try the collatz sequence. Enter a number")
num = int(input())
while num != 1:
    num = collatz(num)
    print(num)
    if num == 1: break
print("ta da!"); input()