Menu
CoddyTech

Guard Clauses

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

When a function needs several checks, nesting one if inside another pushes the real work deeper and deeper:

func buy(gold: int, price: int) -> String:
	if price > 0:
		if gold >= price:
			return "Bought! %d gold left" % (gold - price)
		else:
			return "Not enough gold"
	else:
		return "Invalid price"

A guard clause turns this around. It checks one invalid case at the top of the function and leaves right away with return. The code after the guards runs only with valid values, and it needs no nesting:

func buy(gold: int, price: int) -> String:
	if price <= 0:
		return "Invalid price"
	if gold < price:
		return "Not enough gold"
	return "Bought! %d gold left" % (gold - price)

buy(50, 30) returns Bought! 20 gold left, buy(10, 30) returns Not enough gold and buy(50, 0) returns Invalid price.

The order of the guards matters: the guard that protects a line must come before it. Check the text with is_valid_int() before you use the number, and check for zero before you divide:

func share(coins: int, players: int) -> int:
	if players <= 0:
		return 0
	return coins / players

In a -> void function, a guard is return on its own. Inside a loop, continue works as a guard for one element: it skips an invalid element and the loop goes on with the next one.

challenge icon

Challenge

Easy

Write the function process_data. It takes a string text and returns a string:

  1. If text is not a whole number, return Input must be a number!
  2. If the number is 0, return Cannot divide by zero!
  3. Otherwise, divide 100.0 by the number and return the result with two decimals

For example, process_data("8") returns 12.50, process_data("-5") returns -20.00 and process_data("abc") returns Input must be a number!.

Write the two checks as guard clauses at the top of the function.

Try it yourself

func process_data(text: String):
	# Write code here
	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