我正试着打印一张价值表,告诉科学家在兔子用完笼子之前可以让它们继续繁殖几个月。我不知道在for循环中使用什么范围。我需要它停止一旦兔子的总数超过笼子的数目,即输入。以下是我所拥有的:
cages = int(input("How many cages do you have? "))
print("Month\t", "Adults\t", "Babies\t", "Total")
def fib(n):
if n < 2:
return n
return fib(n-2) + fib(n-1)
n = 1
total = fib(n+2)
adults = fib(n+1)
babies = fib(n)
if total < cages:
## dont know what to put in range here to make the loop stop at the
## correct place
for n in range(cages):
print((n+1), "\t", fib(n + 1), "\t", fib(n), "\t", fib(n+2))
print("You ran out of cages!")“笼子”似乎不是正确的范围,因为这样总数就会比笼子的数量大得多。
发布于 2018-10-18 19:14:53
你需要的是break。试试像这样的东西
for n in range(cages):
total = fib(n+2)
adults = fib(n+1)
babies = fib(n)
if total > cages:
break
print((n+1), "\t", fib(n + 1), "\t", fib(n), "\t", fib(n+2))https://stackoverflow.com/questions/52880914
复制相似问题