You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python实现重复输入数字并判断能否被3整除功能咨询

修正Python整除判断与统计代码的问题

你的代码核心问题是缩进错误:if-else判断逻辑没有被包含在for循环的代码块内,导致循环仅执行输入操作,判断和计数逻辑只会在循环结束后对最后一个输入的数字执行一次,无法统计所有输入的数字。

修正后的代码

q = int(input("How many numbers do you need to check? "))
dt = 0
ndt = 0

for i in range(q):
    w = int(input("Enter number: "))
    if w % 3 == 0:
        print("{} is divisible by 3.".format(w))
        dt += 1
    else:
        print("{} is not divisible by 3.".format(w))
        ndt += 1

print("You entered {} number(s) that are divisible by 3".format(dt))
print("You entered {} number(s) that are not divisible by 3".format(ndt))

关键说明

  • 将if-else块缩进至for循环内部,确保每输入一个数字就立即执行判断和计数操作。
  • 用dt += 1替代dt = dt + 1,写法更简洁,功能完全一致。
  • 修正后运行会和你期望的示例一致:每输入一个数字就输出对应判断结果,最终统计并输出两类数字的总数。

内容的提问来源于stack exchange,提问作者Almighty

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.15 13:55:23