While Examples

Example: Counting Loan Payments

Assume that a loan of \\(225,000 is being repaid with monthly payments of \\\)850, which occur at the end of the month. The loan is collecting interest at a monthly rate of 0.3%. So, at the end of each month, the remaining balance wil be multiplied by 1.003, and then \$850 is deducted from this balance. We can use a while loop to determine the number of monthly payments required to fully repay the loan.

balance = 225000
rate = 0.003
pmt = 950
count = 0

while balance > 0:
    balance = balance * (1 + rate) - pmt
    count += 1
    
print(count)
414

It is very unlikely that amount owed during the last month was exactly \$850. As a result, after the loop finished executing, the balance was likely negative. We can add the payment amount back to the balance to get the amount owed just before the final payment, and thus determine the true size of the last payment.

print(balance + pmt)
807.5215657588019

Example: Guessing Game

Programs often require input from the user. Python’s input() function provides a method of prompting the user for input. For example, consider the following code:

name = input("What is your name? ")

This code will print the string, “What is your name? ” and will then wait for user input. The value entered by the user will then be stored in the variable name.

name = input("What is your name? ")
print("Hello, " + name + "!")
---------------------------------------------------------------------------
StdinNotImplementedError                  Traceback (most recent call last)
<ipython-input-3-f70476670659> in <module>
----> 1 name = input("What is your name? ")
      2 print("Hello, " + name + "!")

~\anaconda3\envs\Python37\lib\site-packages\ipykernel\kernelbase.py in raw_input(self, prompt)
    856         if not self._allow_stdin:
    857             raise StdinNotImplementedError(
--> 858                 "raw_input was called, but this frontend does not support input requests."
    859             )
    860         return self._input_request(str(prompt),

StdinNotImplementedError: raw_input was called, but this frontend does not support input requests.

User input can be combined with while loops to create interactive programs. Here we implement a simple guessing game in which the user is prompted to try to guess a randomly generate number between 0 and 500.

import random
n = random.choice(range(0, 501))

print("I have selected a random number between 0 and 500, inclusive. Can you guess it?")

done = False
count = 1
while done == False:
    
    guess = int(input("Please enter guess number " + str(count) + ": "))
    
    if(guess < n):
        print("Your guess was too small.")
    elif(guess > n):
        print("Your guess was too large.")
    else:
        print("That's it! It took you " + str(count) + " guesses to find the right answer.")
        done = True
        
    count += 1