Search code examples
pythonintcollatz

Traceback error and "argument of type 'int' is not iterable" when trying to use while loop


Im trying to write my first program ever, a collatz sequense program. The code is

input_siffra = input("Input an integer: ")
startsiffra = int(input_siffra)

def Collatz(collatz_number):
    position = (len(str(collatz_number)) - 1)
    if position in collatz_number in (0, 2, 4, 6, 8):
        return (collatz_number / 2)
    else:
        return (collatz_number * 3 + 1)

while startsiffra != 1:
    print(startsiffra)
    Collatz(startsiffra)

What im trying to do here is find a way to tell if the number i put in is even or odd (yes i know there is the % 2 method but im deliberately trying to not use it here to learn) by looking at the last digit in said number, and then do one of two things if its even or odd. Running this gives me two errors, first a traceback for Collatz(startsiffra) and the int error for the line checking if the last number is in a list.


Solution

  • input_siffra = input("Input an integer: ")
    startsiffra = int(input_siffra)
    
    def Collatz(collatz_number):
        position = (len(str(collatz_number)) - 1)
        if collatz_number%10 in (0, 2, 4, 6, 8):
            return (collatz_number / 2)
        else:
            return (collatz_number * 3 + 1)
    
    while startsiffra != 1:
        print(startsiffra)
        startsiffra=Collatz(startsiffra)
    

    This seems to work as you wished. Hope I helped

    EDIT: You can also use this if instead of the one i put in the code. Its what you had been trying to do in you code (without using %)

    if str(collatz_number)[position] in ('0', '2', '4', '6', '8'):