I have a question about the 'continue' function in Python. I wolud like to skip 'Antarctic' in the following list:
continents = = ["Afrika", "Antarktic", "Asien", "Australia", "Europe", "North America", "South America"]
I thought about using the for loop in combination with the 'continue' function but it doesn't work. Maybe I have to transform the list in another format or so.
This was my first guess.
for i in continents:
if i == 1:
continue
print(i)
Thanks in advance.
CodePudding user response:
Given your sample list:
continents = [
"Afrika",
"Antarktic",
"Asien",
"Australia",
"Europe",
"North America",
"South America",
]
You are iterating through this list, so i
is the value of each string as you're going along:
for i in continents: # i: str
So at this point, you just need to compare each string to your value to skip it:
if i == "Antarktic":
continue
CodePudding user response:
Having the list as:
continents = [
"Afrika",
"Antarktic",
"Asien",
"Australia",
"Europe",
"North America",
"South America",
]
These are two of the many approaches that work:
for el in continents:
if el == "Antarktic":
continue
print(el)
for i, el in enumerate(continents):
if i == 1:
continue
print(i, el)
Also, continue
is a statement and not a function. You can read more about it here.
CodePudding user response:
1.First of all the assignment of values in list will give error. ==
is used for checking equal condition. use = for assignment.
continents = ["Afrika", "Antarktic", "Asien", "Australia", "Europe", "North America", "South America"]
for i in continents:
It symbolize that you are iterating over values not indices so according to above for loop the if condn will never met. Two solution for this.
a.
`
for i in continents:
if i == "Antarktic:
continue
print(i)
`
b.
`
for i in range(len(continents)):
if i ==1:
continue
print(i)
`
CodePudding user response:
If I am not wrong, you want to skip the print function, if the value is equals to "Antarctica".
continents = [
"Afrika",
"Antarctica",
"Asien",
"Australia",
"Europe",
"North America",
"South America",
]
# If want to skip based on the value, use below code
for i in continents:
if i == "Antarctica":
continue
else:
print(i)
# If want to skip based on the index, use below code
for i in continents:
if continents.index(i) == 1 :
continue
else:
print(i)
but this is not the perfect scenario for using "continue", anyway it will work.