Process Control Issue

岁酱吖の 提交于 2020-01-11 11:43:48

问题


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

def collatz():
    global number
    if number % 2 == 0:
        number = number // 2
        print(number)
        return number
    else:
        number = 3 * number + 1
        print(number)
        return number

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 collatz() != 1:   # if input(4), the output will be: 4 2 1 4 2 1 
    collatz()


# another way, which works:
while number != 1:  --> # also input(4), the output will be: 4 2 1
    collatz()

回答1:


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


来源:https://stackoverflow.com/questions/44705996/process-control-issue

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!