Except ValueError


Can you help me fixing my Code:

all goes well except my ValueError exception when i input not an integer. Can you help me why this doesn´t work? Thank you :blush:

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


  n = input("Give me a number: ")

except ValueError:
  print("type an int!")

while n != 1:
    n = collatz(int(n))

Hi @stefanbartl215503678

I can see you have an exception handler.

Here’s the docs for the input() function:

Can you see why you might be getting the ValueError?

Here's the relevant bit of the docs...

input([ *prompt* ])

If the prompt argument is present, it is written to standard output without a trailing newline. The function then reads a line from input, converts it to a string (stripping a trailing newline), and returns that. When EOF is read, EOFError is raised. Example:

>>> s = input('--> ') 
--> Monty Python's Flying Circus 
>>> s
 "Monty Python's Flying Circus"

If the readline module was loaded, then input() will use it to provide elaborate line editing and history features.

What do you think would happen if you try and cast a string type to an integer?

@stefanbartl215503678, You only want the while loop to be executed if the input is valid, so put the while loop inside of the try block.