Help needed for collatz conjecture

Hello, I’m a complete newbie both to python and to coding in general.
I’m having trouble with counting the steps necessary to get the number to 1.


```> def steps(number):
       if number == 0 or number < 0:
           steps = 0
           raise ValueError("Only positive integers are allowed")
      else:
           while number != 1:
               if number % 2 == 0:
               number = number / 2        
           else:
               number = (number * 3)+1
               steps += 1
   return steps

I wrote this but the test fails saying: “cannot access local variable ‘steps’ where it is not associated with a value” but I can’t think of another solution.
Any help is much appreciated :)

Because python is indentation sensitive, it’s really hard to read your code. Please edit your post and put the code in “code fences” (3 backticks) like this

This is just plain text

```python
my python code:
    goes here
```

Thank you! I didn’t know how to correctly copy code, hope I fixed it now:)

Suppose number is greater than 0

The lines

steps += 1

and

return steps

each assume steps already has a value. But it does not: the only time you specify an initial value for steps is when number == 0 or number < 0.

1 Like

Thank you! fixed it and passed it :))

@giulizz If you can afford it, I’d highly recommend the Exercism Coding Fundamentals course. This is one of the exercises we look at in detail. If you need a discount etc, please just ask me (jeremy@exercism.org)

Thank you, I’ll look into it

1 Like

hi, so just saw the post and i know its late but still
there are few issues, firstly the scope,

  • Your declared the variable steps inside the if statement, returning it outside the statement is not possible because it doesn’t exist.
    Initialize it at the start of the function.
 def steps(number):
            step_count = 0; # also function name shouldn't be same as the variable name.
  • Second thing is Indentation, u need to work on that.
    hope it helps

Thanks! I’ve also recognized the error and passed it but I was curious about what else is wrong with the indentation

It would help to share all the code in a codeblock. The quoted code looks a bit off but makes it look like the indentation is not 4 spaces.

Sure, here it is:

def steps(number): 
    step = 0
    if (number == 0) or (number < 0):
       raise ValueError("Only positive integers are allowed")
    else:
        while number != 1:
            if number % 2 == 0:
               number = number / 2   
            else:
                number = (number * 3)+1
            step += 1
    return step

The indentation there looks good to me! There’s no indentation issues there.

Great, thanks! I must’ve copied the code wrong before