简体   繁体   中英

How would I get rid of this infinite loop?

##
numOfYears = 0
## Ask user for the CPI
cpi = input("Enter the CPI for July 2015: ")
## If they didn't enter a digit, try again
while not cpi.isdigit():
    print("Bad input")
    cpi = input("Enter the CPI for July 2015: ")
## Convert their number to a float
cpi = float(cpi)
while cpi <= (cpi * 2):
    cpi *= 1.025
    numOfYears += 1
## Display how long it will take the CPI to double
print("Consumer prices will double in " + str(numOfYears) + " years.")

Is there a way to take the number that the user inputs cpi and double it so that while cpi <= (cpi * 2) doesn't give me an infinite loop? Also, is there a way to allow the user to input a floating point number so that it doesn't return the Bad input error? All help is much appreciated.

Others have already explained why you get that infinite loop: You compare cpi to its current value instead of its original value. However, there's more:

  1. The result of numOfYears is independent of cpi
  2. You do not need a loop at all, just use logarithms

So you could just change your code to this:

from math import ceil, log
numOfYears = ceil(log(2) / log(1.025))

This gives you the years until any CPI has doubled given the annual rate of change of 1.025 .


About your other question:

Also, is there a way to allow the user to input a floating point number so that it doesn't return the 'Bad input' error?

You should just try to convert to float and break from the loop as soon as it works.

while True:
    try:
        cpi = float(input("Enter the CPI for July 2015: "))
        break
    except ValueError:
        print("Bad input")

But as I said, for what you are calculating in that script, you do not need that number at all.

You should save the value givent as an input

cpi = float(cpi)
target_cpi = cpi * 2
while cpi <= target_cpi:
    cpi *= 1.025
    numOfYears += 1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM