Click here to Skip to main content
15,903,388 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
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:

Python
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"))
Posted
Updated 30-May-18 20:26pm
v2

1 solution

Quote:
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?

Because with this code you get -1 if first letter is not an operator.
Try
Python
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"))
 
Share this answer
 
Comments
Member 13852296 31-May-18 6:50am    
Thanks alot...works perfectly fine

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900