Kotlin Course

Kotlin Conditions and Loops

A self-study guide for Python 3 compiled from the materials on this site. Primarily intended for those who want to learn the Python programming language from scratch.

if as an Expression

In Kotlin, if is an expression that returns a value — you can use it instead of a ternary operator:

val max = if (a > b) a else b

val grade = if (score >= 90) "A"
    else if (score >= 80) "B"
    else if (score >= 70) "C"
    else "F"

when Expression

when is Kotlin's powerful replacement for switch:

val day = 3
val dayName = when (day) {
    1 -> "Monday"
    2 -> "Tuesday"
    3 -> "Wednesday"
    6, 7 -> "Weekend"
    else -> "Other"
}
println(dayName)  // Wednesday

// when without argument (acts like if-else chain)
when {
    score >= 90 -> println("Excellent!")
    score >= 60 -> println("Passed")
    else -> println("Failed")
}

for Loop with Ranges

for (i in 1..5) print("$i ")      // 1 2 3 4 5
for (i in 1 until 5) print("$i ") // 1 2 3 4
for (i in 5 downTo 1) print("$i ") // 5 4 3 2 1
for (i in 0..10 step 2) print("$i ") // 0 2 4 6 8 10

val fruits = listOf("apple", "banana", "cherry")
for (fruit in fruits) println(fruit)
for ((index, fruit) in fruits.withIndex()) {
    println("$index: $fruit")
}

while and do-while

var i = 0
while (i < 5) {
    print("$i ")
    i++
}

var x = 10
do {
    print("$x ")
    x -= 3
} while (x > 0)

break and continue with Labels

outer@ for (i in 1..3) {
    for (j in 1..3) {
        if (j == 2) continue@outer
        println("$i,$j")
    }
}