【发布时间】:2015-02-06 07:51:03
【问题描述】:
因此,我的任务是验证用户输入的每个 ISBN 10 位数字。我需要确保 1)用户输入不是空白,2)用户输入只是一个整数(我已经完成了),以及 3)他们只输入一位数字。
抱歉,我看到了一些类似的问题,但我想保留 try-except 语句(如果可能的话),所以类似的问题没有太大帮助。
如何验证空白输入并且只输入一位数字?
代码如下:
print("You will be asked to enter an ISBN-10 Number. Please enter it digit by digit.")
ISBN10NumberList = []
ISBN10NumberAdder = 0
for count in range (10):
validInput1 = True
if (count <= 8):
while validInput1 != False:
try:
ISBN10NumberList.append(int(input("Please enter the ISBN digit: ")))
validInput1 = False
except ValueError:
print("That is not a valid input! Please enter a integer only.")
elif (count == 9):
CheckDigit10 = input("Please enter the ISBN digit: ")
print("")
if CheckDigit10 == "X" or CheckDigit10 == "x":
CheckDigit10 = 10
for count in range (0, 9):
ISBN10NumberAdder += int(ISBN10NumberList[count]) * (10 - count)
CheckDigit10 = int(CheckDigit10)
CheckingCheckDigit = 11-(ISBN10NumberAdder % 11)
if (CheckDigit10 == CheckingCheckDigit):
print("This is a valid ISBN!")
else:
print("This is not a valid ISBN!")
【问题讨论】:
-
逐位输入?这是什么模式,Sadism 编程?
-
伊格纳西奥有一个很好的观点。为什么不获取整个输入(作为字符串),逐个字符地迭代它以进行完整性检查,然后在最后执行有效性检查?
-
这样会更容易吗?我该怎么做呢?
-
这似乎是正则表达式的工作。
标签: python validation isbn