[英]python simple function error?
我有一个简单的函数可以执行简单的数学运算。 如果使用导入从另一个脚本中调用此命令,则不会获得任何输出。 如果我删除def function
,一切工作正常。 定义此功能有什么问题? 我是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)
您要将结果返回给调用函数还是将其打印出来? 程序中唯一会return
结果的路径是除法,而执行此操作将永远不会到达print
语句。
如果您想两者都做,则应使该零件弯曲:
print('value is',c)
return c
...达到if
和elif
语句的级别。 不要忘记删除测试代码( result = calci(...)
等)。
原因是,一旦您的代码命中了return
语句,该函数即已完成,其中的任何内容都将不被执行(不是很正确,存在一个称为finally
块的异常处理机制,这是对此的异常,但这不是一个问题)。
补充 :由于您只想打印它,因此删除return
语句并使print
语句凹陷。
函数末尾的缩进似乎是错误的; print
和return 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
您的函数仅在op =='/'时返回。
从这两行中删除几个选项卡,它将起作用。
即
def calci(a, op, b):
...
print('value is',c)
return c
返回部分的缩进不正确,应为低一级。 (这很难描述... 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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.