Home  >  Q&A  >  body text

python - try应该写在for里面还是外面

有个for循环,比方这样

for x in datal:
    print x[0][0]

这个x0可能越界,打算try一下,那么try是应该写在for里面还是外面?求大神赐教

大家讲道理大家讲道理2740 days ago976

reply all(4)I'll reply

  • 怪我咯

    怪我咯2017-04-18 10:21:43

    An exception will occur when printing, so it should be inside

    reply
    0
  • 伊谢尔伦

    伊谢尔伦2017-04-18 10:21:43

    Place it in different locations, the code logic is different, it depends on the specific needs

    Put it inside the loop and when an exception occurs, if the catch exception does not continue to be thrown, the loop will continue
    ; If it is placed outside, the loop will be terminated at the location of the first exception

    reply
    0
  • PHPz

    PHPz2017-04-18 10:21:43

    Put it outside the loop, the performance will be better~

    reply
    0
  • 天蓬老师

    天蓬老师2017-04-18 10:21:43

    You can put it anywhere, but it’s not recommended to put it outside and only try it once, and put it in a loop and try it n times.

    reply
    0
  • Cancelreply