简体   繁体   English

我的程序有错误,无法找出它不起作用的原因

[英]I have an error in my program and cannot find out the reason why it doesn't work

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"))

The indentation is not perfect but I keep getting the value -1. 缩进不是很完美,但我一直得到-1。 I tried removing the else statement and then the program runs perfectly. 我尝试删除else语句,然后程序完美运行。 But I need the -1 to be returned if there is not operator in txt. 但是如果txt中没有运算符,我需要返回-1。 What is the error in my program? 我的程序有什么错误? I am a newbie to Python. 我是Python的新手。 So please spare the hate. 因此,请避免仇恨。

When I run this code I get the intended result, 1. My guess is that the else statement after the for loop is slid in, so is executed if the first symbol isn't an op. 当我运行此代码时,将得到预期的结果:1.我的猜测是for循环后的else语句已插入,因此如果第一个符号不是op则执行该语句。

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"))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM