此代码是来自 picoctf.com 即将举行的比赛的预览。我修改了提供的原始代码,以便允许用户输入,但我无法让测试#2 工作。当输入包含至少一个字母的 10 个字符的字符串时,我希望它打印只能使用数字。目前它尝试将用户输入转换为整数值以将其与实际序列进行比较,但如果存在字母,则测试失败,因为字母无法转换为整数值:
123456789a 产生“invalid literal for int() with base 10 ...”
如何修复这段代码以便正确测试?
**
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")