[英]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:它目前的作用:
"Cannot load page, bad URL."
"Cannot load page, bad URL."
message. 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:其他改进:
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)
。
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.