如何采用不同的输入类型并对每种类型做不同的事情? Python 3.5

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

所以我正在尝试制作一个供个人使用的 Reddit 机器人,作为一个学习项目,但我在为输入添加错误异常时遇到了问题。

这里是完整的源代码:http://pastebin.com/DYiun1ux

这里唯一有问题的部分是

 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

我不确定如何确保输入的用户名有效。谢谢!

python 中的每个输入都将被读取为字符串,因此检查类型总是 return 字符串。如果要检查输入的有效性,请声明一个字符串,例如

charset = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890-_"

然后遍历您的字符串以查看该字母是否在字符集中。如果不是,则输入无效。还要确保输入不超过20个字符。

input 总是 returns 一个字符串。您最好的选择是尝试将结果转换为整数。

try:
    thing_limit = int(thing_limit)
except ValueError:
    print("You need a whole number.")
    sys.exit()
else:
    print("That is a number, thanks.")

reddit 源代码 defines 一个有效的用户名,至少 3 个字符,不超过 20 个字符,并匹配正则表达式 \A[\w-]+\Z.