使用类方法检查的Python输入验证

1 投票
1 回答
1574 浏览
提问于 2025-04-18 04:46

好的,我已经试了大约两个小时,但还是搞不定。我觉得我尝试了几乎所有可能的算法组合,但还是不行。下面是我的情况:

我想在Python中验证键盘输入,主要有两个条件(按优先级排序):

  1. 检查输入是否是整数
  2. 检查输入是否是顶点(这是一个类方法,用来检查给定的数字是否可以在字典的键中找到)

这是我的代码:

def checkVertex(self, x):
    ok = 0
    for key in self.__inv:
        if key == x:
            ok += 1
            break
    for key in self.__outv:
        if key == x:
            ok += 1
            break
    if ok == 2:
        return True
    return False

def checkInt(number):
if number.isdigit() is False:
    return False
return True

def readVertex(msg, graf): <-- this is the issue
"""
msg - string message
graf - Graph() class instance initialised somewhere
invalid_input - string error message
"""
vertex = raw_input(msg)
while checkInt(vertex) is False:
    print invalid_input
    vertex = raw_input(msg)
    if checkInt(vertex) is True:
        vertex = int(vertex)
        if graf.checkVertex(vertex) is True: <-- this bloody line is not working right
            return vertex
        else:
            continue
return int(vertex)

source = readVertex("Give source vertex (by number): ", G)
dest = readVertex("Give destination vertex (by number): ", G)
cost = int(raw_input("Give cost: "))
print G.addEdge(source, dest, cost)

我遇到的问题是,第一个条件是有效的,所以如果我输入一个字母,它会打印错误信息,但如果我输入一个数字,而这个数字不在字典的键中,它仍然会返回这个数字。

所以在上面的代码中,graf.checkVertex(vertex)总是返回True,尽管我知道它应该返回False,因为我在命令行中用相同的输入测试过这个函数,它确实返回了False。

让我给你举个例子,假设我有这个字典:

{0: [], 1: [], 2: [], 3: [], 4: []}

示例的屏幕录制:

在这里输入图片描述

1 个回答

0

你的验证 只在 while checkInt(vertex) is False: 这个条件下运行——如果第一次检查时它是一个有效的整数,你就不会再检查后面的内容了。并不是说 graf.checkVertex(vertex) 这个函数不管用,而是它根本没有被调用。你可以试试这样:

def readVertex(msg, graf, invalid_input):
    """
    msg - string message
    graf - Graph() class instance initialised somewhere
    invalid_input - string error message
    """
    while True:
        vertex = raw_input(msg)
        if checkInt(vertex) and graf.checkVertex(int(vertex)):
            return int(vertex)
        print invalid_input

或者

def readVertex(msg, graf, invalid_input):
    """
    msg - string message
    graf - Graph() class instance initialised somewhere
    invalid_input - string error message
    """
    while True:
        try:
            vertex = int(raw_input(msg))
        except ValueError:
            print invalid_input
        else:
            if graf.checkVertex(vertex):
                return vertex
            print invalid_input

撰写回答