只接受python字符串上的数字

时间:2014-02-01 11:06:57

标签: python

代码确实接受了数字,但如果输入错误两次则会出现错误

isbn= input('Please enter the 10 digit number: ')
while not(len(isbn) == 10 and isbn.isdigit()):
       print('Please make sure you have entered a number which is exactly 10 characters long.')
       isbn=int(input('Please enter the 10 digit number: '))
       continue

else:
    total= 0
    for i in range(len(isbn)):
           total= int(isbn[i])
    calculation=total%11
    digit11=11-calculation
    if digit11==10:
         digit11='X'
iSBNNumber=str(isbn)+str(digit11)
print('Your 11 digit ISBN Number is ' + iSBNNumber)

4 个答案:

答案 0 :(得分:3)

stringisdigit方法:

>>> "1231asd".isdigit()
False
>>> "123131241".isdigit()
True

仅当字符串中的所有字符都是数字时才返回True

因此,您的情况可能是:not (len(isbn) == 10 and isbn.isdigit())

编辑:回答您的新问题(,不要修改类似的问题......)

此处不要使用input,而是raw_inputinput会立即将数字转换为整数。你想保留字符串,因为你将按个别数字操作。

isbn= raw_input('Please enter the 10 digit number: ')
while not(len(isbn) == 10 and isbn.isdigit()):
       print('Please make sure you have entered a number which is exactly 10 characters long.')
       isbn=raw_input('Please enter the 10 digit number: ')

此外,您不需要continue;如果您想跳过部分continue / while循环,则只需使用for

答案 1 :(得分:1)

这里有两个选项:

  1. 检查输入字符串是否长10个字符,并且只包含数字:

    isbn = raw_input("Enter ISBN:")
    if isbn.isdigit() and len(isbn) == 10:
        # go on...
    
  2. 使用正则表达式验证输入。这种方法更灵活,但在理解正则表达式语法方面需要花费额外的精力:

    import re
    
    isbncheck = re.compile(r"^\d{10}$")
    
    isbn = raw_input("Enter ISBN:")
    if isbncheck.match(isbn):
        # go on...
    
  3. 此处"^\d{10}$"表示:“仅由10位数组成的字符串(数字的快捷方式:\d)”

答案 2 :(得分:0)

我认为这将是最简单的解决方案:

def MyFunc():
    isbn=raw_input('Please enter the 10 digit number: ')

    try:
        int(isbn)  # we try to get an int from the input... 

    except:
        print "Try again please."  # ... if we fail - ask user to start all over again
        MyFunc()

    """

    Your code goes here

    """

    return ISBN_number

MyFunc()

答案 3 :(得分:0)

这是这个问题的答案。它可能有一些缩进错误,但我确定你可以解决它毕竟它不需要很多编码技巧。我今天刚刚开始这个网站,并希望用户投票这个答案谢谢 的 * ** * ** * ** * ** * 编码 * ** * ** * ** * ** * ** * ** * ** * ** * ** * ***

isbn= input('Please enter the 10 digit number: ')
while not(len(isbn) == 10 and isbn.isdigit()):
       print('Please make sure you have entered a number which is exactly 10 characters long.')
       isbn=input('Please enter the 10 digit number: ')


else:
     total= 0
     for i in range(len(isbn)):
         total= int(isbn[i])
         calculation=total%11
         digit11=11-calculation
         if digit11==10:
              digit11='X'
iSBNNumber=str(isbn)+str(digit11)
print('Your 11 digit ISBN Number is ' + iSBNNumber)