Python循环异常:数值按20%递减计数无输出无报错排查
问题分析与解决方法
问题描述
用户编写的Python代码如下:
import math user = int(input("Enter a number: ")) times = 0 amount = user while amount != 0: interest = amount * 20 / 100 amount = amount - interest times = times + 1 print(times)
需求是:输入一个数值,每次递减20%,统计直至数值变为0或小于0的次数,预期输出格式为"your number is 6700 and with reduction of 20% in each interval it takes x times to make it 0.",但代码运行后既无输出也无报错。
原因分析
- 死循环导致无法终止:循环条件
amount != 0存在逻辑缺陷。每次将数值乘以0.8(减去20%),非零初始值会无限趋近于0但永远不会精确等于0(例如初始值6700,多次乘0.8后只会无限接近0,不会等于0),循环永远无法结束,print语句自然不会执行。 - 未覆盖数值小于0的场景:原循环只判断是否等于0,没有处理数值递减后小于0的情况,不符合需求。
修正后的代码
user = int(input("Enter a number: ")) times = 0 amount = user while amount > 0: interest = amount * 20 / 100 amount -= interest times += 1 print(f"your number is {user} and with reduction of 20% in each interval it takes {times} times to make it 0.")
修正说明
- 修复循环条件:将
while amount != 0改为while amount > 0,当数值递减到小于等于0时,循环自动终止,避免死循环。 - 匹配预期输出格式:使用f-string动态插入用户输入的数值和统计的次数,替换原代码中硬编码的示例值。
- 清理无用代码:移除未被使用的
import math语句,简化代码。
内容的提问来源于stack exchange,提问作者Ajen Rai
相关产品推荐
相关产品推荐

