我检查了多次,但是我不知道怎么了。
class stack:
def __init__(self):
self.stack=[]
self.limit=5
def isfull():
if len(self.stack)==self.limit:
return True
else:
return False
def isempty():
if len(self.stack)==0:
return True
else:
return False
def push(self,ele):
if self.isfull():
print("stack overflow")
else:
self.stack.append(ele)
def pop(self):
if self.isempty():
print("stack underflow")
else:
print(self.stack.pop())
def peek(self):
if self.isempty():
print("stack empty")
else:
print(self.stack[-1])
def display(self):
if self.isempty():
print("stack underflow")
else:
for i in self.stack:
print (i, end = " ")
print()
s=stack()
while True:
print("1 2 3 4 5")
ch=int (input("entre 12345"))
if ch==1:
ele=int(input("ener input"))
s.push(ele)
elif ch==2:
s.pop()
elif ch==3:
s.peek()
elif ch==4:
s.display()
else:
print("thank you")
break
答案 0 :(得分:1)
您必须使用try / catch / else构造检查/验证输入的数据:
class Stack:
def __init__(self):
self.stack = []
self.limit = 5
def isfull(self):
return len(self.stack) == self.limit
def isempty(self):
return len(self.stack) == 0
def push(self, ele):
if self.isfull():
print("stack overflow")
else:
self.stack.append(ele)
def pop(self):
if self.isempty():
print("stack underflow")
else:
print(self.stack.pop())
def peek(self):
if self.isempty():
print("stack empty")
else:
print(self.stack[-1])
def display(self):
if self.isempty():
print("stack underflow")
else:
for i in self.stack:
print(i, end=" ")
print()
s = Stack()
while True:
try:
ch = int(input('Enter a valid option [1,2,3,4,5]: '))
except ValueError:
print("That's not a valid number!")
else:
if ch == 1:
try:
ele = int(input('Enter a valid number: '))
except ValueError:
print("That's not a valid number!")
else:
s.push(ele)
elif ch == 2:
s.pop()
elif ch == 3:
s.peek()
elif ch == 4:
s.display()
else:
print("thank you")
break