Reputation: 15
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')
Upvotes: 0
Views: 43
Reputation: 30947
Save the initial value of n
in another variable, like
starting_value = n = int(input('n? '))
…
print(starting_value, 'takes', n_steps, 'steps')
Upvotes: 0
Reputation: 33107
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')
Upvotes: 1