1

I am trying to figure this out on my assignment, but I am struggling sooo hard.

So what I need is restricting the user input for variable 'age' to be equal to or greater than 18. I want to display my own error message and terminate the program if the input is either string or less than 18.

Also I have noticed that the program is automatically showing ValueError when letters are inputted because I have used the int() for my input. But I would like to change that error message to my own. I read somewhere to call and check the values first then int() them, so I tried the input() by itself but don't think it worked either.

Here is what I have now for the age portion:

age = int(input('Enter age'))
if not age.isdigit():
    sys.stderr.write('Please enter appropriate age')
    sys.exit(1)
elif age < 18:
    print('You have to be at least 18 years old')
    sys.exit(1)
else:
    age = int(age)

I tried to do something like set the conditions for it to quit, then for other conditions it would keep going.......... but I am not sure if else could go with if not and I don't think it worked :(

Any help is appreciated!!

  • A Pythonic way to implement this is using a try-except on that ValueError -- [see here](https://docs.python.org/3/tutorial/errors.html#handling-exceptions), this link even has almost your exact example! – xjcl May 13 '17 at 21:12
  • @aryamccarthy but this doesn't let me show my error message when str is used as input! It would only show my error message if the age is less than 18, and show the ValueError if other characters are used :( –  May 13 '17 at 21:13
  • That's an easy enough check to add. – Arya McCarthy May 13 '17 at 21:14
  • @xjcl Thank youuuu!! Combined the two and it worked! –  May 13 '17 at 21:18
  • Perhaps a simpler version: https://repl.it/HwjY – David Metcalfe May 13 '17 at 21:31

1 Answers1

-1

Use try and except to handle exceptions, e.g

age = input ()
try:
    age = int(age)
except Exception as err:
    # Add your custom error
    print (err, "Error Message")

And this catches all 3 errors