Skip to content Skip to sidebar Skip to footer

Checking Multiple For Items In A For Loop Python

I've written a code to tell the user that the their brackets are not balanced. I can exactly tell where my code is going wrong. Once it comes across the first situation of brackets

Solution 1:

if you return as soon as something is OK, you won't find the errors further in the string... that's exactly what you're doing in 3 places:

if a =='('andnext==')':
    print("its matched parenthesis")
    returnTrue# let it continue to check the string.

Add a return True at the end of your method: if the loop goes through, then string is OK (actually it's already OK in your current code)

Aside:

  • don't use next for your variable, as it's built-in to get a value from an iterable. I'll use c
  • if next=='(' or next=='{' or next=='[': could be replaced by if c in "({[":
  • for i, next in enumerate (text): you're not using the index, just do for c in text:

Solution 2:

Simply remove your return True statements, since those cause the entire method to return True, before checking the rest of the string. The only time you know you can return True is once you've processed the entire string, so the only return True should be after your for loop finishes.

defisbalanced(text):
    openingbracket=[]
    for i, nextinenumerate (text):
        ifnext=='('ornext=='{'ornext=='[':
            openingbracket.append(next)
        ifnext==')'ornext=='}'ornext==']':
            iflen(openingbracket)==0:
                print("ops only opening brackets")
                returnFalseelse:
                a=openingbracket.pop()
                if a =='('andnext==')':
                    print("its matched parenthesis")
                    returnTrue# REMOVE THIS LINEif a =='{'andnext=='}':
                    print("its matched curly brackets")
                    returnTrue# REMOVE THIS LINEif a =='['andnext==']':
                    print("its matched square")
                    returnTrue# REMOVE THIS LINEelse:
                    print("wrong closing brackets")
                    returnFalseiflen(openingbracket):
        print ("no closing brackets")
        returnFalseelse:
        print("no brackets")
        returnTrue
isbalanced("Hello()(]")

Post a Comment for "Checking Multiple For Items In A For Loop Python"