类方法ch的Python输入验证

2024-06-17 08:16:05 发布

您现在位置:Python中文网/ 问答频道 /正文

好吧,我已经试了2个小时了,但我好像搞不懂。我想我几乎尝试了所有可能的算法组合,但仍然不起作用。接下来是:

我尝试基于两个条件(按优先级排序)验证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,尽管我知道它是有效的,因为我在shell中用相同的输入尝试了这个函数,但它返回了False。在

我给你举个例子,假设我有这样一句话:

^{pr2}$

示例的屏幕录制:

enter image description here


Tags: keyfalsetruenumberinputreturnifis
1条回答
网友
1楼 · 发布于 2024-06-17 08:16:05

您的验证只运行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

或者

^{pr2}$

相关问题 更多 >