Python - 检查用户输入以确保它是一个整数 - 没有字母等

时间:2013-03-21 12:54:14

标签: python

此代码是picoctf.com即将举行的比赛的预览。我修改了提供的原始代码,因此它允许用户输入,但我不能让测试#2工作。当输入一个包含至少一个字母的10个字符的字符串时,我希望它打印只能使用数字。目前它尝试将用户输入转换为整数值以将其与实际序列进行比较,但如果存在字母,则测试失败,因为字母无法转换为整数值:

123456789a产生“带有基数10的int()的无效文字...”

如何修复这段代码以便正确测试?

**

if int(serial) != serial:
            print ("only numbers allowed")
            print ('Failed Test 2')

**

#!/usr/bin/env python
# Your goal is to find the input that will verify your robot's serial number
#solution to keep it handy = 0933427186

serial = input ("Please enter a valid serial number from your RoboCorpIntergalactic purchase")

def check_serial(serial):
    if len(serial) != 10:
        print ('Failed Test 1')
        return False
    if int(serial) != serial:
        print ("only numbers allowed")
        print ('Failed Test 2')
        return False
    if int(serial[0])+int(serial[1]) != 9:
        print ('Failed Test 3')
        return False
    if int(serial[2])*int(serial[3]) != 9:
        print ('Failed Test 4')
        return False
    if int(serial[4])-int(serial[5]) != 2:
        print ('Failed Test 5')
        return False
    if int(serial[5])%int(serial[4]) != 2:
        print ('Failed Test 6')
        return False
    if int(serial[6])/int(serial[7]) != 7:
        print ('Failed Test 7')
        return False
    if int(serial[8])-int(serial[9]) != 2:
        print ('Failed Test 8')
        return False
    if int(serial[7])*int(serial[1]) != 9:
        print ('Failed Test 9')
        return False
    if int(serial[2]) + int(serial[3]) != int(serial[9]):
        print ('Failed Test 10')
        return False
    return True

if check_serial(serial):
    print ("Thank you! Your product has been verified!")
else:
    print ("I'm sorry that is incorrect. Please use a valid RoboCorpIntergalactic serial number")

3 个答案:

答案 0 :(得分:5)

使用str.isdigit()测试所有字符是否都是数字:

>>> 'a1'.isdigit()
False
>>> '11'.isdigit()
True
>>> '1a'.isdigit()
False

可能希望将serial字符串转换为整数序列,以使所有测试更容易:

s_int = [int(d) for d in serial]

然后

if s_int[0] + s_int[1] != 9:

您可以轻松地使用索引,运算符和预期结果构建一系列测试:

import operator

tests = (
    (0, 1, operator.add, 9),
    (2, 3, operator.mul, 9),
    (4, 5, operator.sub, 2),
    (5, 4, operator.mod, 2),
    (6, 7, operator.truediv, 7),
    (8, 9, operator.sub, 2),
    (7, 1, operator.mul, 9),
)

for i, (a, b, op, res) in enumerate(tests, 3):
    if op(s_int[a], s_int[b]) != res:
        print("Failed test {}".format(i))
        return False

答案 1 :(得分:1)

使用 str.isdigit()

  

如果字符串中的所有字符都是数字且at处于,则返回true   至少一个角色,否则为假。

您也可以使用正则表达式:

import re;
if(re.match('\D', serial)):
    print ('Failed Test 2')

答案 2 :(得分:1)

try:
    int(serial)
except ValueError:
    print ("only numbers allowed")
    print ('Failed Test 2')

或遵循Martijn的建议

try:
    s_int = [int(d) for d in serial]
except ValueError:
    s_int = None
    print ("only numbers allowed")
    print ('Failed Test 2')