Loops
ASnake Documentation
Summary :
Loops are control structures that allow you to execute a block of code repeatedly.
Syntax while :
Python's syntax for repeating a code block so long as it is true.
int x 0
while x++ < 3
print x
# result:
# 0
# 1
# 2
Try this code ➤You can read more about while here.
Syntax for :
Python's syntax for iterating over an iterator or generator.
for x in range(3, 0, -1):
print x
# result:
# 3
# 2
# 1
Try this code ➤You can read more about for here.
Syntax loop :
ASnake's loop is a syntax shortcut for a for loop, meant to simplify it.
A simple example:
loop 3 i
# result:
# 0
# 1
# 2
Try this code ➤It works like this:
loopis the keyword that triggers the shortcut.The second element is the iterable to iterate on.
The third element is the iterator variable, which will trigger a default expression if nothing comes after it. The third element is optional
The second element must either be a literal type or a variable that the compiler can infer type. Thus sometimes it is necessary to inform the compiler with type information:
gives2 does return 2
int variable = gives2
loop variable var do var*gives2
# result:
# 0
# 2
Try this code ➤Also works with indentation:
loop (1,2,3) number
number * number
# result:
# 1
# 4
# 9
Try this code ➤Because the third element is optional, you can use it to quickly repeat code:
thing does print 12
loop 2 do thing
# result:
# 12
# 12
Try this code ➤