正如https://stackoverflow.com/a/47478902/9003921
所述我正在使用此代码生成随机数。如果生成的数字小于9,我希望它与它一起打印一个名称,如果数字是9或10,我希望循环中断。
import random
class Stack:
def __init__(self):
self.container = []
def isEmpty(self):
return self.size() == 0
def push(self, item):
self.container.append(item)
def peek(self) :
if self.size()>0 :
return self.container[-1]
else :
return None
def pop(self):
return self.container.pop()
def size(self):
return len(self.container)
def printItem(self, run):
print(self.container[run]) # Prints last item/name
import random
while True:
rand = random.randint(1, 10)
print(rand)
if rand > 8:
break
Names = Stack()
Names.push('Mary')
Names.push('Peter')
Names.push('Bob')
Names.push('John')
Names.push('Kim')
run = -1
while True:
rand = random.randint(1, 10)
print(rand)
if rand > 8:
break
elif rand:
# Calls printItem with run as parameter
Names.printItem(run)
run-=1 # Subtracts one from run
# Sets run to -1 again if all names have been printed
if run<(-1*Names.size()):
run = -1'
当在上面的链接中回答时,它仍然不会打印每个小于9的数字的名称。它给出的样本输出是
5
8
10
4
Kim
7
John
1
Bob
2
Peter
7
Mary
2
Kim
10
和另一个
9
3
Kim
7
John
1
Bob
6
Peter
10
当它是9或10时,没有退出
请帮忙
答案 0 :(得分:0)
实际上您的代码以您想要的方式工作。只是,你对输出感到困惑。让我在你的问题中解释你的第二个输出:
9 -> It breaks the first loop
3 -> rand is 3
Kim -> It prints 3rd item
7 -> rand is 7
John -> It prints 7th item
1 -> rand is 1
Bob -> It prints 1st item
6 -> rand is 6
Peter -> It prints 6th item
10 -> It breaks the second loop
如果你想看得更清楚,我建议你做3件事:
while
循环。这没用。使用以下内容更改printItem
功能
def item_to_str(self, run):
return str(self.container[run])) # Returns last item/name
使用以下命令更改第二个循环:
while True:
rand = random.randint(1, 10)
if rand > 8:
print(rand, "BREAK")
break
else: #same with elif rand < 9:
print(rand, Names.item_to_str(run))
run-=1
if run<(-1*Names.size()):
run = -1'
然后,再次运行您的代码。
你会看到一些输出:
3 Kim
7 John
1 Bob
6 Peter
10 BREAK