Ask coding questions

← Back to all posts
How do you only accept integers and the word “done” only as an input in python?
bmohm90 (0)

So how would you validate that a user only input integers and the word “done”

Comments
hotnewtop
Coder100 (17045)

Simple! Like this:

user = input("Type in a number or done: ")

try:
  num = int(user)
  # todo: add code for when the input is 'number'
except:
  if user != "done":
    print("You were supposed to type in a number or done.")
  # todo: add code for when the input is 'done'
RYANTADIPARTHI (6001)

Solution

you'll have to make two inputs for this, since done and integers are different.

ints = int(input("integer : "))
stri = str(input("string : "))

if ints == 2:
    print("Integer")
elif stri == "done":
    print("Done!")
else:
    print("Nothing.")

maybe, something like that.
That should work

19wintersp (1120)

Here are two ways of validating an integer:

  1. Check for an error when converting:

    data = input()
    try:
      int(data)
    except Exception:
      #not an integer
  2. Use a pattern-matching system, such as RegEx:

    import re
    data = input()
    if re.match("\d+", data):
      #an integer
    else:
      #not an integer