Skip to content
Eman Castillo edited this page Dec 18, 2022 · 1 revision

For-Loops

For loops work as ranges in NHP, with a lower and upper limit having to be stated in order for them to run.

There are two main ways of doing for-loops in NHP: the to method and the within method.

The format for a for-loop is as follows:
for var_name from lower_limit to/within upper_limit:

The to method:

The to method is inclusive of your larger limit. This means that it will include the upper limit as its last repetition.

The example below uses the to method to print out 1 through 10 on a terminal

include "io.nhp"

def main():
	out = io::output()
	for i from 1 to 10:
		out.writeLine(i)

The within method:

The within method, unlike the to method, is exclusive of the upper limit. This means it will stop one short of it.

The example below uses the within method to print 1 through 14.

include "io.nhp"

def main():
	out = io::output()
	for i from 1 within 15:
		out.writeLine(i)

While-Loops

While loops in NHP work similarly to their python counterparts.

An example of a while loop in NHP is the following code, which uses a while-loop to repeat itself until the variable i is true:

include "io.nhp"

def main():
	out = io::output()
	i = false
	n = 0
	while i == false:
		out.writeLine(i)
		n = n + 1
		if n % 2 = 0:
			i = true
Clone this wiki locally