I'm trying to code the Collatz Sequence but for some reason, my while loop is just being completely skipped after the if/else statement in a FUNCTION. Does an else statement skip all other code after it's in a function? I've tried putting the while loop before the if/else and even tried to include the while loop inside the if/else. I'm new to programming.
def collatz():
number = input()
if int(number) % 2 == 0 :
print(int(number) // 2)
else:
print( 3 * int(number) 1 )
while number != 1 :
collatz()
collatz()
CodePudding user response:
You call to input()
returns a string value, therefore the variable number
is a string which will never equal the integer 1
.
So the while number != 1
statement is always true and collatz()
is called again.
You can add the conversion when you read the input and then it will work as you intent (you might need to catch an error if the input cannot be transformed)
def collatz():
number = int(input())
if number % 2 == 0:
print(number // 2)
else:
print(3 * number 1)
while number != 1 :
collatz()
collatz()
CodePudding user response:
You are looking for this i guess. You don't need to write it in a recursive way. Because every time you call your function you will accept a new input so your calculation will never end.
def collatz():
number = int(input())
while number != 1:
if number % 2 == 0:
number = int(number/2)
print(number)
else:
number = int(number*3 1)
print(number)
collatz()
I always cast to int
cause when you divide your number to 2 even it is an even number you will get float.
Here is the output for the number 5:
5
16
8
4
2
1