So I am trying to make a Reddit bot for personal use, as a learning project, and I am having trouble adding error exceptions for inputs.
Here is the entire source code: http://pastebin.com/DYiun1ux
The parts that are solely in question here are
while True:
if type(thing_limit) == int:
print("That is a number, thanks.")
break
elif type(thing_limit) == float:
print("You need a whole number.")
sys.exit()
elif type(thing_limit) == str:
print("You need a whole number.")
sys.exit()
else:
print("That is a number, thanks.")
break
I'm not sure how I would go about making sure that the username that I put in is valid or not. Thanks!
input
always returns a string. Your best choice is trying to convert the result to an integer.
try:
thing_limit = int(thing_limit)
except ValueError:
print("You need a whole number.")
sys.exit()
else:
print("That is a number, thanks.")
Every input in python will be read as a string, so checking the type will always return a string. If you want to check the validity of the input, declare a string with such as
charset = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890-_"
then iterate over your string to see if that letter is in the charset. If it's not, then the input is invalid. Also make sure that the input does not exceed 20 characters.
The reddit source code defines a valid username as one that's at least 3 characters, no more than 20 characters, and matches the regular expression \A[\w-]+\Z
.