有人可以帮助我发现Python的逻辑错误

时间:2017-02-07 18:26:51

标签: python if-statement

我制作了一个简单的堆栈程序,但是我可以输入比用户输入堆栈大小更多的元素。 if len(self.stk)==size语句似乎无效,我无法理解原因。 这是我的代码:

class stack():
    def __init__(self,size):
        self.stk=[]
        self.size = size
    def push(self,item):
        if len(self.stk)==self.size:
            print"OVERFLOW!"
        else:
            self.stk.append(item)
            print "Len of stack is ",len(self.stk)
            print "Size is ",self.size
    def pop(self):
        if self.isempty()==True:
            print "UNDERFLOW"
        else:
            del self.stk[-1]
    def isempty(self):
        if self.stk==[]:
            return True
        else:
            return False
    def display(self):
        print "\nNow going to show you the stack: \n "
        for i in range(len(self.stk)-1,0,-1):
            print self.stk[i]

size = raw_input("Enter size of stack you want: ")
stak = stack(size)
while True:
    choice = int(raw_input("\nEnter \n 1.To push an item \n 2.Pop an item \n 3. Display Stack \n 4.Quit: "))
    if choice == 1:
        elem = raw_input("Enter the element you want to enter: ")
        stak.push(elem)
    if choice == 2:
        stak.pop()
    if choice == 3:
        stak.display()
    if choice==4:
        break

1 个答案:

答案 0 :(得分:3)

您需要将输入强制转换为数字

size = int(raw_input("Enter size of stack you want: "))

或者,因为您正在使用Python2.7:

size = input("Enter size of stack you want: ")

会工作,因为它会评估他们给出的东西,并且(如果给出一个整数)将返回一个整数。

将来,我可能会建议一件事:

添加以下功能,然后您可以随时检查所有变量:

def debug(*args):
    print('Variable debugger output:')
    for arg in args:
        if arg in ["__builtins__", "inspect", "debug"]:
            continue  # skip these variables
        try:
            var = eval(arg)
            print('{0}: {1} {2}'.format(arg, type(var), var))
        # Handles variables not passed as strings
        except (TypeError, NameError):
            print('{0}: {1}'.format(type(arg), arg))

debug(*dir())  # All variables in scope

debug('size', 'self.size')  # Specific variables - Note it accepts both a list
debug(size, self.size)      # of strings or a list of variables

会给你类似的东西:

debug: <type 'function'> <function debug at 0x7fa046a4f938>
in2: <type 'int'> 5
normin: <type 'int'> 23  # normal input
rawin: <type 'str'> 23  # raw input
sys: <type 'module'> <module 'sys' (built-in)>
test: <type 'str'> Hello
testfloat: <type 'float'> 5.234

注意:如果您使用上面的代码,调试将不会显示...这显示了调试器中的函数。