3

I need to accept a number from the user and print the sum. I want the object defined to accept the characters entered by the user to be of integer type only.

I do not want to check the type of the object after the value is entered. I would like a method by which the program doesn't even accept strings or other data types, only integers.

  • 2
    If you're using python 3.5 onward, there's a support for [type hinting](https://docs.python.org/3/library/typing.html) – Nenri May 27 '19 at 06:56
  • "I do not want to check the type of the object after the value is entered" why not? What if the user enters non-number anyways? – Markus Meskanen May 27 '19 at 06:56
  • @Nenri Type hinting does not restrict the type, it just *hints* at what it should be. You could use mypy, but typing is not for validating user input, it's more about documenting code. – Markus Meskanen May 27 '19 at 07:03
  • Yes but as there's no real "type restriction" in another way that doing it ourselves. Type hinting can help. – Nenri May 27 '19 at 07:03
  • 1
    possible duplicate of [python-how-to-only-accept-numbers-as-a-input](https://stackoverflow.com/questions/27516093/python-how-to-only-accept-numbers-as-a-input) – xxbinxx May 27 '19 at 07:05

1 Answers1

1

I'm quite sure you'd be fine with try/except and converting the user's input to an int:

# Repeat until a "break" is issued
while True:

    number = input('Enter number: ')

    # Attempt to convert the input to an integer
    try:
        number = int(number)

    # If there was an error converting...
    except ValueError:
        print("That's not a number! Try again.")

    # Break the loop if no error, i.e. conversion was successful
    else:
        break
Markus Meskanen
  • 19,939
  • 18
  • 80
  • 119