How do you only accept integers and the word “done” only as an input in python?
So how would you validate that a user only input integers and the word “done”
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'
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
Here are two ways of validating an integer:
Check for an error when converting:
data = input() try: int(data) except Exception: #not an integer
Use a pattern-matching system, such as RegEx:
import re data = input() if re.match("\d+", data): #an integer else: #not an integer