The print() built-in function displays the specified string to the output. In this case, we use print() function to show variables n that we calculated and stored previously.
The input() method, can be used to ask the user for input. In this case, we required user to input value of r. The float() method will converts the number into a number with a decimal point.
A variable stores a value that can be referred to or modified later in the program. In this case, we store the constant value of P, and store the value of A and n for future use.
Method 1
When the system encounters the quit() function, it terminates the execution of the program completely. In this case, if value of r is less than 0.5 or more than 10, the system will output the error message and terminate the program.
Comments starts with a "#" symbol, and Python will ignore them. Comment can be used to explain Python code, and make the code more readable.
With the while loop we can execute a set of statements as long as a condition is true. In this case, as long as A is less than 2.0, it will increase the value of n and calculate the value of A. We use pow() function to calculate the value of 1 + (r / 100) to the power of n.
Write a code or draw a flowchart to find the minimum number of years, n, for a sum of money to be doubled when deposited in a bank with interest rate of r % p.a. compounded yearly. The input is r, where 0.5 ≤ r ≤ 10. Give the output, n, rounded up to the nearest year.
X
Method 2
A variable stores a value that can be referred to or modified later in the program. In this case, we store the value of balance and n for future use.
Game Code
00:00
With the while loop we can execute a set of statements as long as a condition is true. In this case, as long as balance is less than 2.0, it will calculate the value of balance with r and increase the value of n.
#input r (with conditions) r = float(input('Input r (0.5<=r<=10): ')) if r < 0.5 or r > 10:     print(f'r needs to satisfy 0.5<=r<=10, please try again. ')     quit() P = 1.0 A = 1.0 n = 0 while A < 2.0:     n = n + 1     A = P * pow(1 + (r / 100), n) print(f'The sum of money is doubled after {n} years.')
#input r (with conditions) r = float(input('Input r (0.5<=r<=10): ')) if r < 0.5 or r > 10:     print(f'r needs to satisfy 0.5<=r<=10, please try again. ')     quit() balance = 1.0 n = 0 while balance<2.0:     balance = balance * (1.0 + 0.01*r)     n = n + 1 print(f'The sum of money is doubled after {n} years.')