Process Control Issue

后端 未结 1 1925
無奈伤痛
無奈伤痛 2021-01-24 15:17

Why doesn\'t the loop end the first time collatz() returns 1?

def collatz():
    global number
    if number % 2 == 0:
        number = number // 2
         


        
相关标签:
1条回答
  • 2021-01-24 15:38

    In your first method, you call collatz() twice in each loop:

    • once in while collatz() != 1:, where the return value gets tested. If it returns 1 at this point, you will exit the loop.
    • a second time inside the body of the loop. This time, the return value doesn't get tested, so even if it is 1, you'll just go back to the while line.

    So, when you input 4, your output is:

    • 4 (your input)
    • 2 (while line)
    • 1 (body - so the loop won't end)
    • 4 (while line)
    • 2 (body)
    • 1 (while line - now the loop ends)

    You could also write your loop like:

    while collatz() != 1:
        pass  # do nothing
    

    A bit of advice:

    • Avoid using global variables, they quickly become evil
    • Separate concerns: for example, let your collatz() function take a number as parameter, and return the next value. Leave the printing to the rest of the code.
    • try not to repeat yourself.

    You could modify it like this, for example:

    def collatz(n):
        if n % 2 == 0:
            n = n // 2
        else:
            n = 3 * number + 1
        return n
    
    try:
        number = int(input('Please enter an integer except zero.\n'))
    except ValueError:
        print("ValueError: invalid value.")
        number = int(input('You must enter an integer except zero.\n'))
    
    
    while True:  # infinite loop
        number = collatz(number)
        print(number)
        if number == 1:
            # we break out of the loop
            break
    
    0 讨论(0)
提交回复
热议问题