Learn
Conditional Expressions
Comparison Operators

To create more complex conditions for our conditionals to evaluate, we can use comparison operators. Comparison operators evaluate the relationship between two values in order to return an expression as true or false.

There are several comparison operators we can use in Kotlin: <, >, >=, and <=.

The less than operator (<) evaluates to true if the value on the left side of the < is smaller than the value on the right:

var username = "beetle" if (username.length < 10) { println("Please choose a longer username.") } // Prints: Please choose a longer username.

For the greater than operator (>), if the value on the left side of the > symbol is larger than the value on the right, the expression returns true:

var username = "beetlejuice_beetlejuice_beetlejuice" if (username.length > 25) { println("Please choose a shorter username.") } // Prints: Please choose a shorter username.

The less than or equal to operator (<=) returns true only if the value on the left is less than or equal to the value on the right:

var liquidTemp = 27 // Fahrenheit if (liquidTemp <= 32) { println("The liquid will freeze.") } else { println("The liquid will remain liquid.") } // Prints: The liquid will freeze.

The greater than or equal to operator >= will return true if the value on the left is greater than or equal to the value on the right:

var liquidTemp = 50 // Fahrenheit if (liquidTemp >= 212) { println("The liquid will vaporize.") } else { println("The liquid will remain liquid.") } // Prints: The liquid will remain liquid.

Instructions

1.

Dungeons & Dragons is a roleplaying game that uses dice to determine the success of a player’s action.

Create an if expression that checks if the value of d20, which represents a 20-sided pair of dice, is greater than or equal to 17.

Inside the if expression, create a println() statement that outputs, "The incantation works and the dragon is defeated."

2.

Create an else expression that contains a println() statement that outputs "The incantation fails and the dragon wins.".

Folder Icon

Take this course for free

Already have an account?