Python 我的程序有一个错误,无法找到它不存在的原因';行不通 def findnextropr(txt): #txt必须是非空字符串。 如果len(txt)
当我运行此代码时,我得到了预期的结果,1。我的猜测是,在for循环之后的else语句是滑入的,如果第一个符号不是op,那么执行else语句Python 我的程序有一个错误,无法找到它不存在的原因';行不通 def findnextropr(txt): #txt必须是非空字符串。 如果len(txt),python,python-3.x,Python,Python 3.x,当我运行此代码时,我得到了预期的结果,1。我的猜测是,在for循环之后的else语句是滑入的,如果第一个符号不是op,那么执行else语句 def findNextOpr(txt): #txt must be a nonempty string. if len(txt)<=0 or not isinstance(txt,str): print("type error: findNextOpr")
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
op=['+','-','*','/']
for i in range(len(txt)):
if txt[i] in op:
return(i)
else:
return(-1)#this is the else statement I keep getting the worng answer with
print(findNextOpr("1+2+3"))
def findnextropr(txt):
#txt必须是非空字符串。
如果len(txt)您的代码似乎完全执行了它应该执行的操作,它将返回1
,这是正确的。我得到的结果与@thierrylahuille相同,您使用的是正确的python版本吗?是的..python 3.6.something此代码也会为我返回1,这是正确的答案。请确保您的代码中所有缩进都是正确的,与其他语言不同,Python在很大程度上依赖于它来知道运行什么,因此,如果在程序中关闭了它,那么它可能是issue@Shesps这是相同的代码,我只是把空格/缩进排成一行。我只是在我的问题帖子中更改了缩进,我希望缩进没有错。代码的酷之处在于你可以试试!希望能为您解决:)
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"
op=['+','-','*','/']
for i in range(len(txt)):
if txt[i] in op:
print(txt[i])
return(i)
else:
return(-1)#this is the else statement I keep getting the worng answer with
print(findNextOpr("1+2+3"))