-2

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
martineau
  • 119,623
  • 25
  • 170
  • 301
  • 2
    you should include your current attempt and explain what "didnt work" means – Sayse May 23 '22 at 11:23
  • Do you mean to just do something like `if Test[i][r]==search and r < (len(Test[i]) - 1)`? – fam-woodpecker May 23 '22 at 11:25
  • You could wrap the if statement in a try and then catch IndexError however it would be better to change the loop so the index error doesn't occur. – Matthew May 23 '22 at 11:27

5 Answers5

1
for row in Test:
    for item in row:
        if item == search:
            # do stuff 

This is a better way to loop through a 2d array. If you need to get the index you could add 2 counter variables to track it. This way prevents the IndexError rather than having to try catch it.

Matthew
  • 163
  • 1
  • 10
0

You have need to indent your if statement and pass an empty block if you aren't running any commands:

try:
    if Test[i][r] == search:
        # Insert code here, and remove pass
        pass
except IndexError:
    r = 0

But it seems you're re-inventing .index() on the first element. You can use:

try:
    print(Test[[x[0] for x in Test].index(search)])
except ValueError:
    print(f"{search} is not in the list")

Examples:

Search: TestName
['TestName', '123', '1', '2.5']
Search: Foo
Foo is not in the list

You could add some QOL aspects to this new method:

  • .strip()
    • To remove whitespace
  • .lower()
    • To be case intensive
  • .join()
    • For a clean output
try:
    print(", ".join(Test[[x[0].lower() for x in Test].index(search.lower().strip())]))
except ValueError:
    print(f"{search} is not in the list")
Search: nametest
NameTest, 321, 10, 5.2
Freddy Mcloughlan
  • 4,129
  • 1
  • 13
  • 29
0

A better implementation of what you propose is through a condition if you make sure that we are within the allowed range:

if r < len(Test[i])

If you still want to do it with try and except you must add those clauses enclosing the exception in which the exception is produced. In this case at the time you access Test[i][r]. NOT ELSEWHERE

try: 
   a = Test[i][r]
except(IndexError):
   a = 0
   print("error")
print(a)
Luis
  • 133
  • 6
0

Why don't you simply try to subscript the Test matrix...

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

You don't need the if in this case.

FLAK-ZOSO
  • 3,873
  • 4
  • 8
  • 28
0

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
Cow
  • 2,543
  • 4
  • 13
  • 25