Validating Input
Part of the Logic & Flow section of Coddy's GDScript journey. Lesson 67 of 78.
Input arrives as text, and int() converts any text without complaining. When the text is not a whole number, you get a wrong value instead of an error:
print(int("abc")) # 0
print(int("12abc")) # 12
print(int("3.14")) # 3So check the text before you convert it. is_valid_int() returns true when the whole text is a whole number:
print("42".is_valid_int()) # true
print("-15".is_valid_int()) # true
print("3.14".is_valid_int()) # false
print("abc".is_valid_int()) # false
print("".is_valid_int()) # falseis_valid_float() does the same for decimal numbers. It also accepts whole numbers, because 5 is a valid float:
print("3.14".is_valid_float()) # true
print("5".is_valid_float()) # true
print("five".is_valid_float()) # falseSpaces count as characters: " 99 ".is_valid_int() is false. Call strip_edges() first when the input may have spaces around it.
A valid number can still be a wrong value. After the conversion, check that it is in the range your program allows:
var text := OS.read_string_from_stdin()
if not text.is_valid_int():
print("Please enter a whole number")
else:
var age := int(text)
if age < 0 or age > 120:
print("Age must be between 0 and 120")
else:
print("Age: ", age)Challenge
EasyThe program reads one line of input. Check it before converting it:
- If it is a whole number, print
You entered:followed by the number - Otherwise, print
Invalid input! Please enter a valid number.
For the input 42, the output is:
You entered: 42For the inputs abc and 3.14, the output is:
Invalid input! Please enter a valid number.Print the converted number, not the text: for the input 007, the output is You entered: 7.
Try it yourself
extends Node
func _ready():
var user_input := OS.read_string_from_stdin()
# Check the input, then print the number or the error message
pass
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Logic & Flow
1Strings In Depth
String MethodsSearching in StringsReplace and TrimSplit and JoinRecap - Username Check4Dictionaries Part 2
Nested DictionariesArrays of DictionariesMerging DictionariesCopying DictionariesRecap - Frequency Counter2Advanced Decision Making
Match With VariablesMatch GuardsArray PatternsDictionary PatternsMembership ChecksRecap - Command Parser5Contact Book Application
Display MenuAdd Contact8Student Records Manager
Project OverviewAdd Student3Multi-dimensional Arrays
2D Arrays BasicsAccessing 2D Array ElementsNested Loops with 2D ArraysRecap - 2D ArraysJagged ArraysCommon 2D Array PatternsRecap - Game Board6Sets with Dictionaries
What is a Set?Dictionary as a SetAdding and RemovingUnion and IntersectionSet DifferenceRecap - Remove Duplicates9Advanced Data Aggregation
Summing ValuesFinding Minimum and MaximumCustom SortingRecap - Dictionary Sorter12Basic Error Handling
What is Error Handling?Validating InputGuard ClausesReturning Error CodesRecap - Safe DivisionPractice on your own: Online GDScript compiler