我试图将它从python 3转换为2.7,我想我可能已经搞砸了缩进。 shell提供了以下错误消息:
line 20, if(operation == '+'), IndentationError: unexpected indent
我希望尽可能保持代码完整,但我看不到错误!啊!
def add(num1, num2):
return num1 + num2
def subtract(num1, num2):
return num1 - num2
def multiply(num1, num2):
return num1 * num2
def divide(num1, num2):
return num1 / num2
def main():
operation = raw_input("What do you want ot do (+,-,*,/): ")
if(operation != '+' and operation != '-' and operation != '*' and operation != '/'):
print "you must enter a valid operation"
else:
var1 = int(raw_input("Enter num1: "))
var2 = int(raw_input("Enter num2: "))
if(operation == '+'):
print add(var1, var2)
elif(operation == '-'):
print sub(var1, var2)
elif(operation == '*'):
print mul(var1, var2)
else(operation == '/'):
print div(var1, var2)
main()
答案 0 :(得分:0)
PEP8建议使用4 space indentation,这是您的计算器代码重新格式化为4个空格:
def add(num1, num2):
return num1 + num2
def subtract(num1, num2):
return num1 - num2
def multiply(num1, num2):
return num1 * num2
def divide(num1, num2):
return num1 / num2
def main():
operation = raw_input("What do you want ot do (+,-,*,/): ")
if(operation != '+' and operation != '-' and
operation != '*' and operation != '/'):
print "you must enter a valid operation"
else:
var1 = int(raw_input("Enter num1: "))
var2 = int(raw_input("Enter num2: "))
if(operation == '+'):
print add(var1, var2)
elif(operation == '-'):
print sub(var1, var2)
elif(operation == '*'):
print mul(var1, var2)
else:
print div(var1, var2)
main()
编译时出现IndentationError异常,因为你有第20行以及出现过度缩进后出现的那些。
之后我发现了else(else = =' /'):)这是无效的,因为它不需要条件,我用它替换了,否则,因为在这个阶段我们非常确定该操作是' /'。
旁注:
正如@Jkdc建议我们也可以使用这种方法检查运算符字符串,在我看来更可读:
if(operation not in ['+', '-', '*', '/']):
print "you must enter a valid operation"
else:
#Rest of the code
基本上,它检查操作符列表中是否找不到操作字符串,而不是在4个条件下单独比较它们。