Search code examples
pythonarraysmultidimensional-arraytry-catchexcept

Is it possible to use the "try" Function on an "if" statement?


In my program I have this 2D array:

Test=[
  ["TestName", "123", "1", "2.5"],
  ["NameTest", "321", "10", "5.2"],
  ["jpoj", "321", "10", "5.2"],
  ["OIAN","oihadIH","oihda","iohda"]
]

And, in a while loop, in a for i in range function, there's this if statement:

if Test[i][r]==search:

(r is just a variable that gets higher each while iteration).

When it gets to this point, if the r variable is too high, it gives an IndexError.

Is there a way I can use something like the try: and except() functions on it?

Here was my failed attempt at it:

try:
    if Test[i][r]==search:
except(IndexError):
    r=0

The whole code is here if you wish to see it:

stop=False
stop2=False
import time

Test=[
  ["TestName", "123", "1", "2.5"],
  ["NameTest", "321", "10", "5.2"],
  ["jpoj", "321", "10", "5.2"],
  ["OIAN","oihadIH","oihda","iohda"]
]
r=0

search=input("Search: ")

for i in range(len(Test)):
  while stop!=True:
    try:
        if Test[i][r]==search:
          print(Test[i])
          stop=True

        else:
          try:
            r=r+1
          except(IndexError):
            r=0
    except(IndexError):
      r=0
      i=0

while stop2!=True:
  try:
    print(Test[0][r]," | ", end='')
  except IndexError:
    stop2=True
  r=r+1

Solution

  • This is my take on this:

    import time
    stop=False
    stop2=False
    
    Test=[
      ["TestName", "123", "1", "2.5"],
      ["NameTest", "321", "10", "5.2"],
      ["jpoj", "321", "10", "5.2"],
      ["OIAN","oihadIH","oihda","iohda"]
    ]
    r=0
    
    search=input("Search: ")
    
    for idx, lst in enumerate(Test):
        if search in lst:
            for index, value in enumerate(lst):
                if search == value:
                    print(f"Word: {search} found in list: {idx} and index: {index}")
    

    Results:

    Search: 10
    Word: 10 found in list: 1 and index: 2
    Word: 10 found in list: 2 and index: 2
    
    Search: OIAN  
    Word: OIAN found in list: 3 and index: 0