Python Forum
Newbie question - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Newbie question (/thread-21439.html)



Newbie question - Shadowlord - Sep-30-2019

I am trying to answer one of the questions in Automate the Boring Stuff with Python. The function (which seems to work correctly) should retun x if an even number and 3*x+1 if an odd number. I am then trying to call the function with a user given integer, calling the function until it gives the answer 1 and then ending the process. When I run it I keep getting the same number (which I think is the return value of the first function call) repeated indefinitely. Can you please tell me where I am going wrong, I suspect it is something to do with scoping rules, but don't know what.

def collatz(x):
    if x%2==0:
        return x
    else:
        return x*3+1
y=int(input("Enter a number\n"))
while True:
    y=collatz(y)
    print(y)
    if y==1:
        break



RE: Newbie question - buran - Sep-30-2019

you want line 6 to be after line 7 (i.e. you want to get user input in the loop)
Although it will work, you may want to use different variable names for user input and value returned by collaz function

EDIT: or maybe I don't understand correctly? Check what the required output should be when even number. I have some recollections if x is even it should return x/2....


RE: Newbie question - Shadowlord - Sep-30-2019

Seems the mistake is not my code which works, but that it should have been x/2 as you said for even in your post. It was of course repeating the first even number it came across in my version. Oops! I've changed return x to return x/2 and it works fine.