简体   繁体   English

对于语句增量并跳过代码的 rest

[英]For statement increment and skip the rest of the code

I have the following code:我有以下代码:

for a in range(0,len(customer_name),1):

     url = "https://whatever_my_url_is.com/" + customer_name[a] + "/"
     
     try:
               page = urllib.request.urlopen(url)
     except:
               print("Cannot load page, bad URL.")
               a = a + 1

    rest of my code

What it currently does:它目前的作用:

  • Goes through each customer, one at a time, and loads their page.遍历每个客户,一次一个,并加载他们的页面。
  • If the URL is bad, I get the "Cannot load page, bad URL."如果 URL 错误,我会收到"Cannot load page, bad URL." message.信息。
  • The rest of my code continues like normal.我的代码的 rest 继续正常运行。

What I want it to do is immediately stop what it's doing and move to the next customer_name on the list, not continue the rest of the code.我想要它做的是立即停止它正在做的事情并移动到列表中的下一个customer_name而不是继续代码的 rest。

You can use continue您可以使用continue

for a in range(0,len(customer_name),1):

     url = "https://whatever_my_url_is.com/" + customer_name[a] + "/"
     
     try:
               page = urllib.request.urlopen(url)
     except:
               print("Cannot load page, bad URL.")
               continue

    rest of my code

An else clause may be used within a try statement, see Python doc :可以在 try 语句中使用 else 子句,请参阅Python doc

try1_stmt ::=  "try" ":" suite
               ("except" [expression] ":" suite)+
               ["else" ":" suite]

Therefore you can also write your code as follows:因此,您也可以按如下方式编写代码:

for a in customer_name:
     url = 'https://whatever_my_url_is.com/{}/'.format(a)
     try:
               page = urllib.request.urlopen(url)
     except:
               print("Cannot load page, bad URL.")
     else:
        rest of my Code

Other improvements:其他改进:

  1. range(start, stop, step) may be written as range(stop) if start is 0 and step is 1.如果 start 为 0 且 step 为 1,则range(start, stop, step)可以写为range(stop)

  2. You may use a sequence item directly.您可以直接使用序列项。 instead of代替

    for index in range(len(sequence)): print(sequence[index])

    you should use:你应该使用:

     for item in iterable: print(item)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM