r/inventwithpython • u/[deleted] • Apr 05 '16
Ch.3 Collatz Function
I am having a little trouble with global variables. What I am trying to do is let the user know the number of operations performed before the number 1 was achieved. Is it possible to pull out a local variable of n to the global space, and if so how?
print("This is console module")
def collatz(number):
global n
while number != 1:
if number%2 == 0:
number = number//2
n = n+1
else:
number = 3*number+1
n = n+1
print('Input a number')
number = int(input())
print('It took ' + str(n) + ' operations to achieve your number = 1')1
u/ordnance1987 Apr 05 '16
Are you supposed to use global variables? What is the output you get and what is the expected output? Is this all your code? You never call the collatz function so It doesn't do anything but print things and get user input.
1
u/AlSweigart Apr 08 '16
You'll need to add n = 0 in the global scope (or inside the function) to create the variable. Otherwise, when the n = n+1 line runs, the n variable won't exist and it'll give you that error.
Also, remember to actually call the collatz() function. The def statement only defines the function, it doesn't run it.
1
u/Atrament_ Apr 05 '16
This works and is fundamentally the same. Except I added a call to
collatz()at the end and initialized the globalnat the beginning.Whenever possible, please avoid global variables, they will mess your code when you'll be writing bigger, longer codes. Here is what I have, arguably cleaner. (the cache dictionary exists so you can do a while loop in the
__main__section later on)