3

I'm very new to any sort of coding, currently using python 3.3. I've managed to run the Collatz Sequence accurately in python with the following:

while True: # The main game loop.
number = int(input('Enter number:\n'))  
def collatz(number):
    while number !=1:
        if number % 2==0: #even numbers
            number=number//2
            print(number)
        elif number % 2!=0: #odd numbers
            number=number*3+1
            print(number)
collatz(number)

However, I'm unsure of how and where to add a ValueError strong, for when the user enters a non-integer, something like the following:

except ValueError:
    print('Only integers accepted.')

I'm very new to python, so if any answers could have a little explanation I'd be very appreciative. Thanks

biscuit
  • 29
  • 2

5 Answers5

3

Put it at the very very top. Parameter constraints should always happen as soon as possible, so that you don't waste time running code you're just going to error out of.

def progress(percentage):
    if percentage < 0 or percentage > 100:
        raise ValueError
    #  logic
Michael Bianconi
  • 5,072
  • 1
  • 10
  • 25
  • 2
    Of note, this checks the parameter after collatz() is called, and raises the ValueError if appropriate. This would still require you to catch the exception, assuming you’d want to prompt the user for valid input, and not have the program crash due to the exception being raised. The example provided in https://stackoverflow.com/a/61789224/3570769 checks the parameter prior to calling collatz(), and loops back to prompt the user for input again. – Logan Elandt May 14 '20 at 04:38
  • 1
    Your explanation of why parameter constraints should occur is very useful for a newbie like me, thanks very much! I went with Avishka's answer as I have learned about try statements, but im curious to learn about how the percentage stuff works too. I have so long ahead of me – biscuit May 14 '20 at 06:19
  • 1
    Agree with the occurrence of parameter constraints, here the `percentage` is just a parameter passed into `progress()` function. In `if` statement it checks whether the percentage is in range or not. If it isn't in range it'll raise the exceptionError: Value error and terminate the process. – Avishka Dambawinna May 14 '20 at 06:32
3

I assumed that you're referring to Exception Handling, Validation part must be done in the beginning.

    while True: # The main game loop.
        
        try:
            number = int(input('Enter number:\n'))
   
        except ValueError:
            print("Only integers accepted! Please try again ...")
        else:
            collatz(number)
#output:
#
#Enter number:
#abc
#Only integers accepted! Please try again ...
#Enter number:
#5
#16
#8
#4
#2
#1
#Enter number:

But program will continue looping, termination conditions needed.

Avishka Dambawinna
  • 1,180
  • 1
  • 13
  • 29
0
number = None

while number != int():
    try:
        number = int(input("Enter number: "))
        break
    except:
        print("Enter a valid Number")

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

collatz(number)
0
def collatz():

    try:
        number = int(input("Enter number: "))

        while True:
            if number == 1 or number == 0:
                break

            elif number % 2 == 0:
                number = number // 2
                print(number)

            elif number % 2 == 1:
                number = 3 * number + 1
                print(number)

    except:
        print("Enter in a valid number")


collatz()
David Buck
  • 3,752
  • 35
  • 31
  • 35
  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-ask). – Community Sep 17 '21 at 06:02
-1

Try this:

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

while True:
    try:
        number = int(input("Enter a Number or type 0 to exit: "))
        if number == 0:
            break
        while True:
            if number != 1:
                number = collatz(number)
            else:
                break
    except ValueError:
        print("Enter an integer number")
Bhargav Rao
  • 50,140
  • 28
  • 121
  • 140
  • 1
    I would not recommend such approach — `try` section should be as narrow as possible. For example this error message would be irrelevant if a `ValueError` is raised in the `collatz` function. – Sergey Shubin Jun 28 '21 at 14:03