0

I know I need a for loop, I am trying to print the input number(as a maximum) and then print the number of steps it took to reach 1. The current program prints the input number and the nember of steps for that input number, I need it to print every input number and corresponding steps for each number to 1 with related steps. If i input 2 it should say it 2 takes 1 steps then 1 takes 0 steps.

n = int(input('n? '))
n_steps = 0
num=n
while n > 1:
        n_steps+=1
        if n % 2 == 0:
            n = n // 2
        else:
            n = n * 3 + 1
print(str(num) + ' takes ' + str(n_steps) + ' steps')
4
  • 2
    Sorry I don't understand. What is an input example and what is the corresponding expected output (in a specific form and numbers, rather than a description)? Commented Oct 16, 2021 at 5:54
  • What do you mean by "every input number", there is only one input. If you want to run you code X times or indefinitely, use for _ in range(X): or while True to wrap all your code Commented Oct 16, 2021 at 5:55
  • Its the collatz count and a input example would be 5 and the output would be 1 takes 0 steps, 2 takes 1 steps, 3 takes 7 steps, 4 takes 2 steps, 5 takes 5 steps, each on there own line Commented Oct 16, 2021 at 6:12
  • put num1=n above the n_steps=0 and put everything below num1=n into for loop that counts down from num1 and at the end of the iteration decrease num. that should do the trick Commented Oct 16, 2021 at 6:24

1 Answer 1

1

are you trying to do something like this?

num = int(input('n? '))
for i in range(num, 0, -1):
    n_steps = 0
    n = i
    while n > 1:
        n_steps += 1
        if n % 2 == 0:
            n = n // 2
        else:
            n = n * 3 + 1
    print(str(i) + ' takes ' + str(n_steps) + ' steps')
Sign up to request clarification or add additional context in comments.

11 Comments

That is the answer I am looking for thank you, but one detail, I am assuming it has to do with the range function inputs. I need the answer in reverse. same numbers and output just in opposite print out order.
if you look at the range function it goes like this. range(start,stop,step) so range(5,0,-1) will count from 5 down to 1. if you want opposite you can just use range(5) and it will count from 0 to 4. have fun with it. and if it helped i'm kindly asking to accept my answer
that works but I get the last printed line with 0 takes 0 steps, how can I eliminate that last output.
I just figured it out with your previous answer, thank you.... I just put for i in range(1,num+1): that gave me the output I wanted.
i copy pasted the exact code that i tested and it sure does not print 0 takes 0 because range is itself counting down to 1 and there's nothing that'll make i 0. please always try the provided code first as is, before modifying it.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.