Trying to write a function but don't known how to start.

trying to make a function that ask the user for the current population and displays the population after 1/2 years unitil it reaches 1 million at a rate of 8% per year. for example

Year 1, population 864000
Year 2, population 933120
Year 3, population 1007769

I been told to use a while loop. but the problem is I don't known how to set the question out in python codes. Please help!

Recommended Answers

All 6 Replies

Okay, so look at your sentence just here:

ask the user for the current population and displays the population after 1/2 years unitil it reaches 1 million at a rate of 8% per year. for example

That tells you exactly what you need to do, first: Ask the user for the current population
This is done with just an input statement

#designed for python 3.x but will work with 2.x
population = int(input("Enter the population"))

So now to the while loop, a while loop needs a condition on which it stops.. We have that here:Until it reaches 1 million

while population < 1000000:
    #do stuff

So not to give everything away, try having a go at that and see what you get, try and make it work! :)

def populationGrowth():
    x = input("What is the current population: ")
    y = 0.08
    x = 0
    while x < 1000000:
        x = int(x * (1+ y))
        print (x)

I made the code above but when I call up the function it displays the 0 value up to a million and I can't see what I have done wrong.

Cause in line 4 of the program you reset the input to 0!? :P Delete line 4

If you want to start with the population after 1/2 year, then every year you have to change your code to this (Python2 or Python3) ...

def populationGrowth():
    x = int(input("What is the current population: "))
    y = 0.08
    x = int(x * (1 + y/2))  # population after 1/2 year
    print( x )
    while x < 1000000:
        x = int(x * (1+ y))
        print( x )

I get the value as output but I want the output to show the following

Year 1, population 864000
Year 2, population 933120
Year 3, population 1007769

How to I get the function to output Year 1 together with the value and so on.

I made another variable call Year = Year + 1 and included this in the print statement but i get a snytex error.

Please help

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.