python 3.4
我正在编写一个验证函数来检查用户的输入。在一种情况下,我试图验证用户输入了 0 到 99 之间的整数。
一切都以字符串形式出现,因此假设我们有一个整数的字符串表示,明显的起点是这样的:
isinstance(int(userinput), int)
但假设用户犯错的方式没有尽头,假设他或她不小心输入了“2l”。这实际上是一个字符串,而不是整数的字符串表示。上面的 isinstance()
检查此结果:
ValueError: invalid literal for int() with base 10: '2l'
我不知道如何解释这种可能性。
最佳答案
使用 try
和 except
,您甚至不需要 isinstance
检查:
userinput = None
try:
userinput = int(input("type a number"))
except ValueError:
print ("invalid input")
if userinput is not None:
# rest of code
关于python - 区分字符串和字符串表示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31795465/