Home>

I'm a Python beginner.

Using a While Statement in Python,
"We have created a program that saves twice as much the next day, such as 1 yen for the first day, 2 yen for the next day, and 4 yen for the next day, and displays up to the day when the total exceeds 10,000 yen."

I tried the following description, but

day = 0
yen = 0
while yen<10000:

day + = 1
yen + = 1

new_word = "The deposit amount on the {} day is {}." .Format (day, yen)
print (new_word)
yen * = 2

=========

Despite assuming the following as the execution result

The deposit amount on the first day is 1.
The deposit amount on the second day is 3.
The deposit amount on the third day is 7.
The deposit amount on the 4th day is 15.
The deposit amount on the 5th day is 31.
The deposit amount on the 6th day is 63.
The deposit amount on the 7th day is 127.
The deposit amount on the 8th day is 255.
The deposit amount on the 9th day is 511.
The deposit amount on the 10th day is 1023.
The deposit amount on the 11th day is 2047.
The deposit amount on the 12th day is 4095.
The deposit amount on the 13th day is 8191.
The deposit amount on the 14th day is 16383.

The last description of "14th day" below cannot be displayed.

The deposit amount on the 14th day is 16383.

I've been doing a lot of trial and error, but it doesn't work because the idea is different.
Could anyone help me?
Thanks for your cooperation.

  • Answer # 1

    Yen over 10000 is not printed because yen is doubled after print, so yen over the last 10000 is not printed.
    Also, it was complicated because the total and daily savings were set to the same variable, so I divided them.

    day = 0
    save_yen = 1 # Daily savings
    sum_yen = 0 # Total savings
    while sum_yen<10000:
        day + = 1
        sum_yen + = save_yen
        new_word = "The deposit amount on the {} day is {}." .Format (day, sum_yen)
        print (new_word)
        save_yen * = 2
    # The deposit amount on the first day is 1.
    # The deposit amount on the second day is 3.
    # The deposit amount on the 3rd day is 7.
    # The deposit amount on the 4th day is 15.
    # The deposit amount on the 5th day is 31.
    # The deposit amount on the 6th day is 63.
    # The deposit amount on the 7th day is 127.
    # The deposit amount on the 8th day is 255.
    # The deposit amount on the 9th day is 511.
    # The deposit amount on the 10th day is 1023.
    # The deposit amount on the 11th day is 2047.
    # The deposit amount on the 12th day is 4095.
    # The deposit amount on the 13th day is 8191.
    # The deposit amount on the 14th day is 16383.

  • Answer # 2

    In the while statement, the continuation condition is checked at the beginning of the loop.
    So, the loop ends when it exceeds 10,000.

    To do what you want, check if you've exceeded 10,000 at the end of the loop, and break out of the loop if you do.

    # Then, while true, make an infinite loop