【问题标题】:How do I rectify 'Unexpected Indent" error in Python? [duplicate]如何纠正 Python 中的“意外缩进”错误? [重复]
【发布时间】:2020-07-31 14:03:59
【问题描述】:

这是我的代码:

def c_to_f(c):    
    f = c*(9/5) + 32
    return f
    
c = input("Please enter the temperature in celsius: ")
    if c< -273.15:
        return "That temperature is not achievable."
    else:
        return f
print("Here's your temperature in Fahrenheit: ", c_to_f(c)) 

终端,在执行此代码时显示:

if c< -273.15:                                                                                                                            
    ^                                                                                                                                         
IndentationError: unexpected indent 

我该如何解决这个错误?

【问题讨论】:

  • 这意味着你的 if c&lt; -273.15: 循环在不应该缩进的时候被缩进了

标签: python indentation


【解决方案1】:

需要修复它抛出的回溯线上方的线:

def c_to_f(c):    
    f = c*(9/5) + 32
    print(f)

    # the input line here needs to be indented to be consistent within your code block and consider adding an int() if you are expecting a value
    c = int(input("Please enter the temperature in celsius: "))
    if c < -273.15:
        print("That temperature is not achievable.")
    else:
        print(f)

    # and the print() statement needs to be indented as well 
    print("Here's your temperature in Fahrenheit: ", c_to_f(c))

查看link,它遵循 PEP8 缩进规则(4 个空格)。

【讨论】:

  • return f 只是停止一切,我认为这不是好的功能
  • true,应该使用print() 来防止函数在到达 if/else 语句之前结束。
猜你喜欢
  • 2011-05-14
  • 1970-01-01
  • 2020-12-17
  • 2022-06-10
  • 1970-01-01
  • 2015-11-07
  • 1970-01-01
  • 2012-10-25
  • 1970-01-01
相关资源
最近更新 更多