Search code examples
pythoncollatz

ATBSWP, Chapter 3, Collatz Sequence. Why does the while loop run when condition is already met?


if the user inputs the number 1, then the while loop shouldn't run since 1 = 1, correct?

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.')

Solution

  • Initially, the type of n is considered as str so "1" != 1 hence the condition is satisfied. Look at this example https://code.hackerearth.com/0acb47j