218k views
15 votes
In "Rabbitville", the rabbit population squares each year. e.g. If you start with 4 rabbits, you'll have 16 in 1 year, and 256 in 2 years. Once the population exceeds 10,000 bunnies, food will be scarce, and population will begin to decrease.

Write a function years_till_no_carrots that includes a WHILE loop. Given a single integer (# of starting rabbits) as an input, your function should output the number of whole years until the number of rabbits becomes larger than 10000. e.g. years_till_no_carrots(4) = 3 (start with 4 rabbits, population greather than 10000 & food scarce in 3 years)

User Powege
by
3.4k points

1 Answer

7 votes

Answer:

In Python:

def years_till_no_carrots(n):

year = 0

while(n <= 10000):

n=n**2

year = year + 1

return year

Step-by-step explanation:

First, we define the function

def years_till_no_carrots(n):

Next, the number of years is initialized to 0

year = 0

The following while loop is iterated until the population (n) exceeds 10000

while(n <= 10000):

This squares the population

n=n**2

The number of years is then increased by 1, on each successive iteration

year = year + 1

This returns the number of years

return year

To call the function from main, use (e.g): print(years_till_no_carrots(4))

User Vijay Vepakomma
by
4.0k points