pythonstringpython-3.xfunctioncollatz

Implementing the collatz function using Python


I am currently having trouble completing this challenge in "Automate the boring stuff":

Image of the challenge

My code is:

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


print('What number would you like to use?')
seqNum = input()
number = int(seqNum)
i = number

while i > 1:
    collatz(seqNum)
    print(number)

And I am getting this error:

"Traceback (most recent call last):
  File "C:/Users/Administrative/AppData/Local/Programs/Python/Python36-32/collatzSeq.py", line 15, in <module>
    collatz(seqNum)
  File "C:/Users/Administrative/AppData/Local/Programs/Python/Python36-32/collatzSeq.py", line 3, in collatz
    if (seqNum % 2 == 0):
TypeError: not all arguments converted during string formatting"

I know I am doing SOMETHING wrong with how I wrote my code but I don't understand what it is exactly. Any and all help is greatly appreciated!

Also I am using python 3.


Solution

    1. You're doing arithmetic on a string, not an integer.

    2. There's no need to have a global variable. Pass an argument to a function, and have it return a value accordingly.


    def collatz(number):
        if (number % 2 == 0):
            return number // 2
    
        elif (number % 2 == 1):
            return 3 * number + 1
    
    print('What number would you like to use?')
    
    i = int(input())
    while i > 1:     
        i = collatz(i)
        print(i)