Menu
CoddyTech

Recap - Safe Division

Part of the Logic & Flow section of Coddy's GDScript journey. Lesson 70 of 78.

challenge icon

Challenge

Easy

The program reads two lines of input: a dividend and a divisor. Both should be numbers, with or without decimals.

  1. If either line is not a valid number, print Error: Invalid number
  2. Otherwise, call the function safe_divide(a, b), which you write above _ready(). It takes two floats and returns a dictionary:
    • {"ok": false, "error": "Cannot divide by zero"} when b is 0
    • {"ok": true, "value": a / b} otherwise
  3. If the result is ok, print Division result: and the value with two decimals. Otherwise, print Error: and the error message.

For the inputs 10 and 4, the output is:

Division result: 2.50

For the inputs 100 and 0, the output is:

Error: Cannot divide by zero

Try it yourself

extends Node

# Write the safe_divide function here


func _ready():
	var first := OS.read_string_from_stdin()
	var second := OS.read_string_from_stdin()
	# Check both inputs, call safe_divide and print the result
	pass

All lessons in Logic & Flow

Practice on your own: Online GDScript compiler