Basic Python Programming Exercise: A Penny Doubled Every Day

See Python: Tips and Tricks for similar articles.

Challenge: You will receive a gift of 1 penny today. Tomorrow, you will receive double that (2 cents). The next day, you will again receive double that (4 cents). And, so on. Once you have received a total of more than $1 million, your gifts will stop. Write code to determine how many days you will be receiving gifts, how much the last gift will be, and how much you will receive in total.

Give it a try and then check out the possible solution below the image.

Python in Coins

One Possible Solution

money, gift, day = 0, 0.01, 1
while True:
    money += gift
    if money >= 1000000:
        break
    gift *= 2
    day += 1

print(f"On day {day}, your gift of ${gift:,} will bring your total to ${money:,}.")

This will output: “On day 27, your gift of $671,088.64 will bring your total to $1,342,177.27.”