While Loop
Part of the Fundamentals section of Coddy's GDScript journey. Lesson 44 of 92.
A for loop runs once for every number in a range. A while loop keeps running as long as a condition is true:
var count := 3
while count > 0:
print(count)
count -= 1
print("Go!")3
2
1
Go!The condition is checked before every iteration. When count becomes 0, count > 0 is false, so the loop stops and the program continues after it. If the condition is false from the start, the block never runs.
The block must change something the condition depends on. Here count -= 1 brings count closer to 0. Without it, the condition would stay true and the loop would never end.
Use while when you do not know in advance how many iterations you need. For example, this finds the smallest power of 2 that is greater than 27:
var number := 27
var power_of_two := 1
while power_of_two <= number:
power_of_two *= 2
print(power_of_two)power_of_two doubles on each iteration: 2, 4, 8, 16, 32. At 32, power_of_two <= number is false, so the program prints 32.
Challenge
EasyThe program reads one decimal number into number.
Use a while loop to divide number by 2 as long as it is greater than or equal to 3.5. Then print the result, which is the first value smaller than 3.5.
For example, for the input 15 the values are 15, 7.5, 3.75 and 1.875, so the program prints:
1.875If the input is already smaller than 3.5, print it unchanged. Do not use a for loop.
Try it yourself
extends Node
func _ready():
var number := float(OS.read_string_from_stdin())
# Halve number while it is 3.5 or more, then print it
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
4Operators Part 1
Arithmetic OperatorsInteger DivisionModulo OperatorArithmetic ShortcutsRecap - Simple MathComparison Operators10Functions
Declare a FunctionArgumentsReturnReturn TypesRecap - Sigma FunctionRecap - Validation FunctionDefault Values5Operators Part 2
Logical Operators Part 1Logical Operators Part 2Recap - Simple LogicLogical Operators Part 3Ternary OperatorPractice on your own: Online GDScript compiler