Menu
CoddyTech

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")) # 3

So 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()) # false

is_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()) # false

Spaces 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 icon

Challenge

Easy

The 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: 42

For 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
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Logic & Flow

Practice on your own: Online GDScript compiler