[英]Python - Check user input to make sure it is an integer - no letters, etc
This code is a preview from an upcoming competition at picoctf.com. 该代码是来自picoctf.com即将进行的竞赛的预览。 I modified the original code provided so it allows for user input, but I can't get Test #2 to work.
我修改了提供的原始代码,以便允许用户输入,但是我无法使Test#2正常工作。 When a string of 10 characters is entered with at least one letter, I want it to print that only numbers may be used.
当输入一个包含至少一个字母的10个字符的字符串时,我希望它打印出只能使用数字的形式。 Currently it tries to convert the user input to an integer value to compare it to the actual serial, but if there is a letter present the test fails since a letter can't be converted to a integer value:
当前,它尝试将用户输入转换为整数值,以将其与实际序列进行比较,但是如果存在字母,则测试失败,因为字母不能转换为整数值:
123456789a yields "invalid literal for int() with base 10..." 123456789a产生“以10为底的int()的无效文字...”
How can I fix this piece of code so that it tests correctly? 如何修复这段代码,使其正确测试?
** **
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")
Use str.isdigit()
to test if all characters are digits: 使用
str.isdigit()
测试所有字符是否都是数字:
>>> 'a1'.isdigit()
False
>>> '11'.isdigit()
True
>>> '1a'.isdigit()
False
You may want to turn your serial
string into a sequence of integers to make all your tests easier: 您可能需要将
serial
字符串转换为整数序列,以使所有测试变得更加容易:
s_int = [int(d) for d in serial]
then 然后
if s_int[0] + s_int[1] != 9:
etc. 等等
You could easily build a sequence of tests with indices, an operator and the expected outcome: 您可以轻松地构建一系列包含索引,运算符和预期结果的测试:
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
Use str.isdigit()
使用
str.isdigit()
Return true if all characters in the string are digits and there is at least one character, false otherwise.
如果字符串中的所有字符均为数字并且至少包含一个字符,则返回true,否则返回false。
You could use a regular expression as well: 您也可以使用正则表达式:
import re;
if(re.match('\D', serial)):
print ('Failed Test 2')
try:
int(serial)
except ValueError:
print ("only numbers allowed")
print ('Failed Test 2')
or following Martijn's suggestion 或遵循Martijn的建议
try:
s_int = [int(d) for d in serial]
except ValueError:
s_int = None
print ("only numbers allowed")
print ('Failed Test 2')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.