0

I am trying to get the number I input plus the number of steps it took to get to 1. With this code the number of steps works but my input keeps returning the number 1, not what is typed in. I know this is simple, just missing why my variable never changes to the input. I am also trying to treat input as a maximum, so I was trying to add a for loop to contain this all to print every number and steps from input number to 1.

n = int(input('n? '))
n_steps = 0

while n > 1:
        n_steps+=1
        if n % 2 == 0:
                n = n // 2
        else:
                n = n * 3 + 1
        
print(str(n) + ' takes ' + str(n_steps) + ' steps')
wjandrea
  • 28,235
  • 9
  • 60
  • 81
  • 1
    Start logging, and start small. add some `print(n, n_steps)` in your while loop, and call it with n=1. Then 2. Then 3. What do you see happening? This is something you can solve all on your own by simply _explicitly_ looking at what your code's doing at each step. We know what should happen for 1, 2, and 3: what do you see happening instead? – Mike 'Pomax' Kamermans Oct 16 '21 at 03:48
  • thanks, that is how I should of done it and my professor also explained it the same way. – user16545663 Oct 16 '21 at 04:03
  • could you expand your answer a little more? – user16545663 Oct 16 '21 at 04:30

2 Answers2

1

You're changing n in the loop while n > 1. Simply make a copy.

start = n

while n > 1:
    ...
        
print(start, 'takes', n_steps, 'steps')
wjandrea
  • 28,235
  • 9
  • 60
  • 81
  • A second question related to this is what for loop would I need to print every number and corresponding step from my input to number 1. So an input of 5 would say 5 takes 5 steps, then it would print 4 takes 2 steps till it reaches 1 takes 0 steps. I know a for loop containing my original while loop is a good place to start. – user16545663 Oct 16 '21 at 04:37
  • @user16545663 See [this question](/q/869885/4518341) – wjandrea Oct 16 '21 at 04:41
0

Save the initial value of n in another variable, like

starting_value = n = int(input('n? '))

…

print(starting_value, 'takes', n_steps, 'steps')
wjandrea
  • 28,235
  • 9
  • 60
  • 81
Kirk Strauser
  • 30,189
  • 5
  • 49
  • 65