##
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.")
有没有一种方法可以将用户输入的数字cpi
乘以两倍,从而while cpi <= (cpi * 2)
不会给我无限循环?另外,是否有一种方法可以允许用户输入浮点数,以便它不返回Bad input
错误?非常感谢所有帮助。
其他人已经解释了为什么会出现无限循环:您将cpi
其与当前值进行比较,而不是其原始值。但是,还有更多:
numOfYears
独立于cpi
因此,您可以将代码更改为此:
from math import ceil, log
numOfYears = ceil(log(2) / log(1.025))
给定您的年数,直到CPI的年变化率达到任何CPI的两倍1.025
。
关于您的其他问题:
另外,是否有一种方法允许用户输入浮点数,以使它不返回“错误输入”错误?
您应该在工作后try
立即将其转换为float并break
从循环中转换。
while True:
try:
cpi = float(input("Enter the CPI for July 2015: "))
break
except ValueError:
print("Bad input")
但是正如我所说,对于您在该脚本中计算的内容,您根本不需要该数字。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句