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

Python计算器代码IndentationError问题求助:程序无法运行

解决Python计算器代码的缩进错误问题

你的代码出现IndentationError是因为elif语句的缩进和前面的if语句层级不一致,Python要求同一级别的控制语句(if/elif/else)必须保持相同的缩进量,它们内部的代码块再单独缩进一级。

修复后的完整代码如下:

op = input("which operation would you like to use (type m for multiply d for divide s for subtract a for addition): ")
first_number = float(input("please enter your first number: "))
second_number = float(input("please enter your second number: "))
if op.upper() == "M":
    print(first_number * second_number)
elif op.upper() == "D":
    print(first_number / second_number)
elif op.upper() == "S":
    print(first_number - second_number)
elif op.upper() == "A":
    print(first_number + second_number)
else:
    print("the operation you entered is not available")

关键修复点:

  • 将所有elif和if、else对齐,确保它们处于同一缩进层级(推荐用4个空格作为Python的缩进单位)
  • 优化了操作符判断逻辑:只需要把输入转为大写(或小写)一次,就能匹配大小写输入,无需同时判断upper()和lower()
  • 补充了实际运算逻辑,替换原来仅打印操作名称的代码,实现计算器的核心功能

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 18:15:16