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
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
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
It works like this:
1. loop
is the keyword that triggers the shortcut. 2. The second element is the iterable to iterate on. 3. 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
Also works with indentation:
loop (1,2,3) number
number * number
# result:
# 1
# 4
# 9
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