0

I have this code:

def collatz(number):
    if number % 2 == 0:
        print(number//2)
    elif number % 2 == 1:
        print(3 * number + 1)

try:
    while True: # The main program loop.
        print('please enter a number')
        person = input()
        int(person)
        b = collatz(int(person))
        if b == 1:
            sys.exit()
except ValueError:
    print('You must enter an integer')

Why doesn't the program exit when the input is 1? How can I fix it?

Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153
  • 1
    The condition `number % 2 == 1` is true when `number` is 1, so to catch that special case, add an `elif number == 1` block prior to that. – John Bollinger Jul 10 '22 at 23:28
  • Welcome to Stack Overflow. In this program, `b` is never equal to `1` because `b` is never equal to *any integer at all*. Instead, the value `None` is assigned to `b`. Please see the linked duplicate to understand. – Karl Knechtel Jul 10 '22 at 23:47
  • I fixed the code example based on the original version of your post, and also edited it to ask the question directly. For future reference, please read [ask] and the [formatting help](https://stackoverflow.com/help/formatting). – Karl Knechtel Jul 10 '22 at 23:52
  • Also: are you sure that you want to *ask for another number* each time through the loop? Shouldn't it instead repeat the calculation *with the `b` result* until it reaches `1`? – Karl Knechtel Jul 10 '22 at 23:57

1 Answers1

0

Your code has a few syntax errors. Here is some code without the syntax errors. I added some comments to help you understand :)

def collatz(number):
    if number == 1: # Checks if input is 1
        return -1
    if number % 2 == 0:
        return(number/2)
    elif number % 2 == 1:
        return(3 * number + 1)
try:
    while True: # The main program loop.
        print('please enter a number')
        person = int(input())
        b = collatz(person)
        print(int(b)) # Print out the result
        if b == -1:
            break # If the special case of 1 happens, break out of the loop
except:
    print('You must enter an integer')
Wynder
  • 93
  • 8
  • The syntax was fine, but OP had some difficulty posting the code properly - I went back to the original version of the post and fixed it. The key change here is `return`ing values rather than `print`ing them. It would be better in general to explain that sort of thing directly; but this question did not need to be answered, because it is commonly asked and we have a reference duplicate. – Karl Knechtel Jul 10 '22 at 23:53
  • As an aside, there is not any need to add an extra case to the logic. `Special cases aren't special enough`. – Karl Knechtel Jul 10 '22 at 23:57