简体   繁体   English

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

[英]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.

相关问题 如何使程序检查用户输入是否在随机整数的5、10、15、20等范围内? - How do I make my program check whether user input is within 5,10,15,20, etc of the random integer? Python如何在用户输入中检查连续字母? - Python how can you check for consecutive letters in a user input? python,使用if循环来确保用户输入是数字,然后操纵数字 - python, using if loop to make sure user input is a number then manipulate number 如何确保用户只能在 Python 中输入某些字符? - How to make sure a user can only input certain characters in Python? Python 检查 integer 输入 - Python check for integer input 验证用户输入作为点的坐标,并确保它可以是 integer,同时浮动或负 - Validate the user input as coordinate for point and make sure that it can be an integer, float or negative at the same time Python:如何检查用户输入的整数是否与列表中的项目不匹配? - python: how to check the integer input by user match the item in the list of not? 用户输入字母时输入失败。 我想检查一下以确保他们输入了一个号码 - Input failing when user inputs a letter. I want to check to make sure they have put in a number 创建循环以检查变量以确保其为正整数 - Creating a loop to check a variable to make sure it is a positive integer 如何确保我的代码继续循环,同时只接受来自用户输入的整数值? - How can I make sure my code continues to loop while only accepting integer values from the user input?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM