How to take different input types and do something different with each? Python 3.5

允我心安 提交于 2020-01-06 22:04:13

问题


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!


回答1:


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.")



回答2:


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.




回答3:


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.



来源:https://stackoverflow.com/questions/33601703/how-to-take-different-input-types-and-do-something-different-with-each-python-3

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!