本文介绍了有没有人可以帮助我在Python程序中找到错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在我的程序中, 如果我删除return-1语句,我会得到正确的答案,但否则它会一直返回-1。它为什么一直这样做?
我尝试过:
In my program, if I delete the return-1 statement I get the right answer but otherwise it keeps returning -1. Why does it keep doing so?
What I have tried:
def findNextOpr(txt):
#txt must be a nonempty string.
if len(txt)<=0 or not isinstance(txt,str):
print("type error: findNextOpr")
return "type error: findNextOpr"
#In this exercise +, -, *, / are all the 4 operators
#The function returns -1 if there is no operator in txt,
#otherwise returns the position of the leftmost operator
#--- continue the rest of the code here ----#
op=['+','-','*','/']
for i in range(len(txt)):
if txt[i] in op:
return(i)
else:
return(-1)
print(findNextOpr("1+2+3"))
推荐答案
引用:
在我的程序中,如果我删除t他返回1声明我得到正确的答案,但否则它会一直返回-1。为什么会一直这样做?
In my program, if I delete the return-1 statement I get the right answer but otherwise it keeps returning -1. Why does it keep doing so?
因为如果第一个字母不是运算符,这个代码就会得到-1。
试试
Because with this code you get -1 if first letter is not an operator.
Try
def findNextOpr(txt):
#txt must be a nonempty string.
if len(txt)<=0 or not isinstance(txt,str):
print("type error: findNextOpr")
return "type error: findNextOpr"
#In this exercise +, -, *, / are all the 4 operators
#The function returns -1 if there is no operator in txt,
#otherwise returns the position of the leftmost operator
#--- continue the rest of the code here ----#
op=['+','-','*','/']
for i in range(len(txt)):
if txt[i] in op:
return(i)
return(-1)
print(findNextOpr("1+2+3"))
这篇关于有没有人可以帮助我在Python程序中找到错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!