如何要求输入验证为10位整数?

0 投票
4 回答
3820 浏览
提问于 2025-04-18 04:49

我正在制作一个ISBN校验位的程序。不过,我已经设置了程序只接受长度为10的值,但如果我输入10个字母,它就会崩溃。

有没有人知道该怎么解决这个问题?

我的代码:

isbnnumber = input('Please input your 10 digit book no. : ')
while len(isbnnumber) != 10:
    print('You have not entered a 10 digit value! Please try again.')
    isbnnumber = input('Please input your 10 digit book no. : ')
else:
    no1 = int(isbnnumber[0])*11
    no2 = int(isbnnumber[1])*10... etc...

非常感谢大家的帮助。

4 个回答

0

你可以把你的while循环的条件换成一个更复杂的条件,这个条件可以用来检查数字,比如:

while not isbnnumber.isdigit() or len(isbnnumber) != 10:    
0

使用正则表达式,你可以精确地检查一个字符串是否符合特定的格式。

import re

m = re.match(r'^\d{10}$', isbn)
if m:
    # we have 10 digits!

这里的正则表达式是\d{10}。其中\d表示你在寻找一个数字,而{10}则表示你需要恰好十个这样的数字。^表示字符串的开始,$表示字符串的结束。

使用正则表达式并不总是你需要的,如果你第一次接触它们,可能需要一些时间来理解。不过,正则表达式是开发中最强大的工具之一。

1

请注意,不仅仅有ISBN-10,还有ISBN-13(实际上在全球范围内更常用)。另外,ISBN-10并不一定都是数字:其中有一个数字是校验位,它可能会是字母“X”(在这种情况下,它的数值是10)。同时,别忘了检查那些校验位;它们是有原因存在的。

所以我建议你写一些辅助函数:

def is_valid_isbn(isbn):
    return is_valid_isbn10(isbn) or is_valid_isbn13(isbn)

def is_valid_isbn10(isbn):
    # left as an exercise
    return len(...) and isbn10_validate_checksum(isbn)

def is_valid_isbn13(isbn):
    # left as an exercise
    return len(...) and isbn13_validate_checksum(isbn)

然后按照下面的方式实现你的输入循环:

valid_isbn=False
while not valid_isbn:
    isbn = input('Please input your ISBN: ')
    valid_isbn = is_valid_isbn(isbn) and isbn # and part is optional, little trick to save your isbn directly into the valid_isbn variable when valid, for later use.
3

你可以使用 str.isdigit 来检查一个字符串是否全部由数字组成:

while len(isbnnumber) != 10 or not isbnnumber.isdigit():

下面是一个示例:

>>> '123'.isdigit()
True
>>> '123a'.isdigit()
False
>>>
>>>
>>> isbnnumber = input('Please input your 10 digit book no. : ')
Please input your 10 digit book no. : 123
>>> while len(isbnnumber) != 10 or not isbnnumber.isdigit():
...     print('You have not entered a 10 digit value! Please try again.')
...     isbnnumber = input('Please input your 10 digit book no. : ')
...
You have not entered a 10 digit value! Please try again.
Please input your 10 digit book no. : 123456789
You have not entered a 10 digit value! Please try again.
Please input your 10 digit book no. : 123456789a
You have not entered a 10 digit value! Please try again.
Please input your 10 digit book no. : 1234567890
>>>

撰写回答