2010-06-06 132 views
0

我有一个简单的功能来做简单的数学运算。如果我使用导入从另一个脚本调用此函数,则不会得到任何输出。如果我删除def function,一切工作正常。定义这个函数有什么问题?我是Python的新手。python简单功能错误?

def calci(a, op, b): 
    if op == '+': 
     c = a + b 
    elif op == '-': 
     c = a-b 
    elif op == '*': 
     c= a*b 
    elif op =='/': 
     if(b == 0): 
      print('can\'t divide') 
      c = a/b 
      print('value is',c) 
      return c 
result = calci(12,'+', 12) 
print(result) 

回答

3

是否要将结果返回给调用函数或打印出来?通过您的程序导致return的唯一途径是划分,当您这样做时,您将永远达不到print声明。

如果你想两者都做,你应该迪登部分:

print('value is',c) 
return c 

...到ifelif语句的水平。不要忘记删除您的测试代码(result = calci(...)等)。

的原因是,一旦你的代码击中return声明,这就是它的功能 - 闲来无事就会被执行(并不完全正确,有一个异常处理机制称为finally块是一个例外,但这不是问题)。

添加:既然您只想打印它,请删除return声明并注册print声明。

+0

我想打印出来,而不是把它的功能,当它din't工作我试图返回价值! – 2010-06-06 05:38:43

+0

是在最后缩进是米奇,所以它打印NONE,现在它的工作....... – 2010-06-06 05:42:49

3

您在函数结尾处的缩进似乎是错误的; printreturn c仅在op == '/'时才会发生,而如果b == 0只归于c。最后应该是:

elif op =='/': 
    if(b == 0): 
     print('can\'t divide') # You should probably return here instead of falling through to the assignment 

    c = a/b 


print('value is',c) 
return c 
+0

现在返回太工作了,谢谢.... – 2010-06-06 05:43:21

1

您的函数只返回如果op =='/'。

从这两行删除几个选项卡,它将工作。

def calci(a, op, b): 

    ... 

    print('value is',c) 
    return c 
1

返回部分的压痕是不正确,它应该是低一个级别。 (我知道这很难形容...... Python的缩进语法的缺陷)

下面是正确的代码:

def calci(a, op, b): 

    if op == '+': 
     c = a + b 

    elif op == '-': 
     c = a-b 

    elif op == '*': 
     c= a*b 

    elif op =='/': 
     if(b == 0): 
      print('can\'t divide') 
      return 0 

     c = a/b 


    print('value is',c) 
    return c 

result = calci(12,'+', 12) 

print(result)