Reputation: 9
I know there are multiple posts on this question. But I could not post my code in any other way except by asking a question. Can someone please help me understand how I can stop n from being input into the collatz function each time the global scope executes.
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. (Amazingly enough, this sequence actually works for any integer—sooner or later, using this sequence, you’ll arrive at 1! Even mathematicians aren’t sure why. Your program is exploring what’s called the Collatz sequence, sometimes called “the simplest impossible math problem.”)# Remember to convert the return value from input() to an integer with the int() function; otherwise, it will be a string value. desired output
3 10 5 16 8 4 2 1
Input Validation Add try and except statements to the previous project to detect whether the user types in a noninteger string. Normally, the int() function will raise a ValueError error if it is passed a noninteger string, as in int('puppy'). In the except clause, print a message to the user saying they must enter an integer.
def collatz(number):
if number%2==0:
number=number//2
print(number)
elif number%2==1:
number=3*number+1
print(number)
print('Enter number: ')
n=int(input())
while n!=1:
collatz(n)
Upvotes: 0
Views: 149
Reputation: 1
It's true that there is an infinite loop and your n
has to be changed on every iteration of while
loop.
Also, I would loop on True
and use break
statement, instead of n != 1
as a condition in a while
statement (see code below). Because it's formally working, but makes first loop iteration with a string, like this: '3' != 1
(which evaluates to True of course and works further).
So the working version may be like this (with input validation added, see try/except
statements):
def collatz(number):
if number % 2 == 0:
return number // 2
elif number % 2 == 1:
return 3 * number + 1
print('Enter number:')
try:
n = input()
while True:
n = collatz(int(n))
print(n)
if n == 1:
break
except ValueError:
print('Please enter a number')
Upvotes: -2
Reputation: 31
You‘ve created an infinite loop, since your „n“ doesn‘t change within the loop and „n!=1“ is never met as long as the user doesn’t input “1” in the beginning.
Try this:
def collatz(number):
if number % 2 == 0:
number = number // 2
else:
number = 3 * number + 1
print(number)
return number
n = int(input("Enter number: "))
while n != 1:
n = collatz(n)
Upvotes: 3