Inside code it is possible to use continue and break:
break statement terminates the loop without executing the else clause’s code
continue statement skips the rest of code's statements and continues with the next item, or with the else clause if there is no next item
Notes:
for fetches all items from iterable by firstly converting it to iterable by iter() then calling next() on it.
Example of usecase of "break/else":
courses =get_subscribed_courses(request.user)# all courses of this userfor session in task.sessions.all():# task.sessions - all sessions where this task assignedif session.course in courses:# session belongs to assigned course - task is "valid"breakelse:returnredirect(reverse('list_hometasks'))# redirect to the list of tasks# Returning rendered page with task:returnrender(request, template_name, context)
Here is a monster-kind example which aims to show all usecases of for loop. You can use it as a base for your experiments:
🪄 Code:
for x inrange(1, 15):print(x, "\t: ", end="")if x in [8,9,10]:print("<---SKIPPING LINE--->")continue# immediately go on next iteration of xif x %2:print("Even number", end="")else:print("Odd number", end="")if x ==12:print("\nBYE BYE!!! (break called!)")break# completely go out from for loopprint(" ... EOL!")# will not triggered if 8 and 10else:# run this block only if no break statement calledprint("No break called -- number 12 was NOT FOUND")
📟 Output:
1 : Even number ... EOL!
2 : Odd number ... EOL!
3 : Even number ... EOL!
4 : Odd number ... EOL!
5 : Even number ... EOL!
6 : Odd number ... EOL!
7 : Even number ... EOL!
8 : <---SKIPPING LINE--->
9 : <---SKIPPING LINE--->
10 : <---SKIPPING LINE--->
11 : Even number ... EOL!
12 : Odd number
BYE BYE!!! (break called!)
One more example for for-else loop - selection of DB:
range() returns iterable object needed for arithmetic progression. It is most often used in for loops. The arguments must be plain integers. If the step argument is omitted, it defaults to 1
Returns an enumerate object which will yield tuples index, item from given iterable (a sequence, an iterator, or some other object which supports iteration)
🪄 Code:
for index, girl inenumerate(["Olya", "Sveta", "Anna", "Maria"], start=1):print("Girl number {} is {}".format(index, girl))
📟 Output:
Girl number 1 is Olya
Girl number 2 is Sveta
Girl number 3 is Anna
Girl number 4 is Maria