ATBSWP,第3章,Collat​​z序列。为什么在满足条件时运行while循环?

时间:2017-07-11 20:05:20

标签: python collatz

如果用户输入数字1,那么while循环不应该从1 = 1开始运行,是否正确?

def collatz(number):

    if number % 2 == 0:
        print(number // 2)
        return number // 2

    elif number % 2 == 1:
        result = 3 * number + 1
        print(result)
        return result

try:
    n = input('Give me a number: ') #user inputs number, saved to n
    while n != 1: #function repeats while number is not equal to 1
        n = collatz(int(n)) #this is what actually calls the function
except ValueError:
    print('Please use whole numbers only.')

1 个答案:

答案 0 :(得分:0)

最初,n的类型被认为是str,因此" 1" != 1 因此条件得到满足。 请看这个示例https://code.hackerearth.com/0acb47j