Python Forum
3 conditions to check and return
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
3 conditions to check and return
#1
i want to check/return for 3 conditions, it loops shortest str and finds diff in other
1. if difference is immediate before end of range, return index, exit
2. if string length is same and index loop is done and matches str2, return 'identical', exit
3. Else just return idex+1 which means the short loop ended and every letter was same so next letter of longer str is the diff, just return idex + 1

but my last print statement always print. not sure how to end this "just return this if other 2 cond. aren't met". hope i am making sense

str1= "kitti cat"
str2= 'kitti catt'
lenStr1= len(str1)
lenStr2= len(str2)

#find shortest str and use it as loop range
if lenStr1 >= lenStr2:
    str= str2
else:
    str= str1
        
# loop each character of shortest string, compare to same index of longer string
# if any difference, exit and return index of difference
for idx in range(len(str)):
    a= str1[idx]
    b= str2[idx]
    if a != b:      #immeditely exit, since non-match found
        print(idx)
        break
    else:
       if len(str1) == len(str2) and idx == len(str1)-1: #if no difference print 'identical'
            print("identical")
            break

print(idx+1) #if other 2 conditions are not met, just return idx+1 which is the last possibility
Reply
#2
If you wrap the code in a function, you can use return instead of break; if I understand you correctly, I think that should satisfy your requirement.
Reply
#3
are you saying if i make it a func and place return it wont include the last line if a condition is met before?

its the last statement or condition it keep printing even if i include the 'break' statement in other condition
Reply
#4
i added an extra else: after the last condition or matching the original For loop. so if the first 2 dont break the loop this last one will... thanks for the reply
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  isinstance() always return true for object type check Yoki91 2 2,553 Jul-22-2020, 06:52 PM
Last Post: Yoki91
  How does while-If-elif-else-If loop conditions check run mrhopeedu 2 1,772 Oct-27-2019, 04:56 AM
Last Post: mrhopeedu
  How do you check if something exists or doesn't in the conditions of an if? Klar 1 2,505 Dec-15-2017, 03:47 PM
Last Post: sparkz_alot

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020