Using while loops and variables
<p>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:</p>

<blockquote>
  <p>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.</p>
</blockquote>

<p>My code:</p>

<pre><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
</code></pre>

<p>The output gives me an infinite loop:</p>

<pre><code>Type an integer: 
10
5
5
5
5
5
5
5
5
...
</code></pre>

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

<pre><code> while(True):
    num=collatz(num)
    if num == 1:
        break
</code></pre>

<p>Output:</p>

<pre><code>Type an integer: 
5
16
8
4
2
1
</code></pre>

<p>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.</p>

<p>Your code:</p>

<pre><code>while(True):
    if collatz(num) == 1:
        break
</code></pre>

<p>didn't work because everytime <code>collatz</code> 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.</p>

<p>When you do <code>num = collatz(num)</code>, the value of <code>num</code> 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 <code>num</code> becomes 1 and exit the loop.</p>

python variables while-loop