tadm123
tadm123

Reputation: 8787

Using while loops and variables

I'm trying to write a collatz program from the 'Automate the Boring Stuff with Python book', but have ran into some problems. I'm using python 3.5.2. Here's the project outline:

Write a function named collatz() that has one parameter named number. If number is even, then collatz() should print number // 2 and return this value. If number is odd, then collatz() should print and return 3 * number + 1. Then write a program that lets the user type in an integer and that keeps calling collatz() on that number until the function returns the value 1.

My code:

def collatz(number):
    if number % 2 == 0:     #its even
        print(number // 2)
        return number // 2
    elif number % 2 == 1:   #its odd
        print(3*number+1)
        return 3*number+1


print('Type an integer: ')
num=int(input())

while(True):
   if collatz(num) == 1:
        break

 # Or even simpler:
 # while(collatz(num) != 1):
 #       pass

The output gives me an infinite loop:

Type an integer: 
10
5
5
5
5
5
5
5
5
...

But when I break it down and use a variable to store the return value, it works:

 while(True):
    num=collatz(num)
    if num == 1:
        break

Output:

Type an integer: 
5
16
8
4
2
1

Why is it? I don't understand why the first program doesn't work. Both are similar but I just chose to test the return value directly in my original program instead of using variables. I'd appreciate any help, Thanks.

Upvotes: 0

Views: 87

Answers (1)

怀春춘
怀春춘

Reputation: 307

Your code:

while(True):
    if collatz(num) == 1:
        break

didn't work because everytime collatz gets called it gets called with the same value of num and as a result returns the same number again and again. That number is not 1, so you have an infinite loop.

When you do num = collatz(num), the value of num is changed the first time the function is called. The new value is then passed to the second time the function is called, and so on. So eventually you reach a point when the value of num becomes 1 and exit the loop.

Upvotes: 2

Related Questions