goasef
goasef

Reputation: 5

Loop is not repeating

I am trying to make this "algorithm", which will take the number and get it down to 4, 2, 1. If anyone have seen the youtube video regarding this math problem, they will understand.

done = False

while True:
    num = int(input("Enter a number: "))  
    if (num % 2) == 0:  
        print(num/2)  
    else: 
        print(num * 3 + 1)
    if num == 1 or 2 or 4:
        break

The output is this algorithm not repeating itself. If I type in number 5 it will x3+1, and print only 16. What I want is it doing this, but keep going till the number is either 1,2 or 4. Hope yall can help :D

Upvotes: 0

Views: 112

Answers (3)

sametatila
sametatila

Reputation: 56

I think you want to repeat num/2 or num*3+1 every output. If you use odd number like 7, it calculates 22 and 22 is a even number and 22 is calculated 11 and it returns 34 and so on. I figure it out like this. But it always ends with 4 :)

done = False
num = int(input("Enter a number: "))
while True:
    if (num % 2) == 0:  
        num/=2
        print(num)
    else:
        num = num * 3 + 1
        print(num)
    if int(num) in [1,2,4]:
        break

Upvotes: 0

Jochem Schulenklopper
Jochem Schulenklopper

Reputation: 6934

The error is in line if num == 1 or 2 or 4:. That always evaluates to True and thus breaks your loop.

Your intention is to have if num == 1 or num == 2 or num == 4:. Or if num in (1,2,4): to be more concise.

(Explanation of your mistake: the if statement has an expression that is being tested. You're chaining a couple of expressions with the or operator, resulting in if expr1 or expr2 or expr3. The if-expression is True if any of those OR'd expressions is True.

Your expr1 is num == 1 which is True only if num equals 1.

Your expr2 is 2 which is True always (!).

Your expr3 is 4 which is True always.

So, your if-expression is always evaluating to True.)

Upvotes: 2

Creative_Username
Creative_Username

Reputation: 11

It isn't testing for all three of those numbers (1, 2 and 4).

Here's the fixed code:

done = False

while True:
    num = int(input("Enter a number: "))  
    if (num % 2) == 0:  
        print(num/2)  
    else: 
        print(num * 3 + 1)
    if num == 1:
        break
    if num == 2:
        break
    if num == 4:
        break

Upvotes: 0

Related Questions