Conditions

Condition is the way we ask question in our code and change up what we do based answer of that question. Word 'if' is really common keyword across programming language.

A simple example :

if balance > 1000 {
    print("You earn interest in this account.")
}

'balance > 1000' is what we called condition. It will always result in either true or false. Code above tell computer to print "You earn interest in this account." IF balance bigger than 1000. What happen when balance is lower than 1000? Computer will ignore it and continue to next statement.

Checking Equality

Sometimes we want to know if a variable is equal with our condition. To do that, we do not use a single equal sign. It maybe look right, but it's not. Remeber, in programming language, equal sign means assigning value. Instead, we use double equal sign ('==').

//wrong
if balance = 1000 {
    print("You earn interest in this account.")
}

//right
if balance == 1000 {
    print("You earn interest in this account.")
}

And to check if something is not equal, we use exclamation mark and equal sign ('!=')

if balance != 1000 {
    print("You earn interest in this account.")
}

Code Blocks

We need to group our statement in code blocks, so computer know which statement need to be executed when true or false. The most common way to write code blocks is by using a curly braces ('{ }') like in example before. You have a opening curly braces, ending curly braces, and statements to executed between them. Remember, for each opening sign, you need to write the closing sign. They have to always in pair.

If/Else

Now, what if you want to do something when condition returning false? Well, 'if' can be paired with 'else', which will executed if the condition is false.

if balance > 1000 {
    //execute this only if true
    print("You earn interest in this account.")
} else {
    //execute this only if false
    print("Sorry, you not earn interest.")
}

If your balance lower than 1000, computer will print "Sorry, you not earn interest." You have to know even though 'if' can be paired with or without 'else', 'else' doesn't work that way. You have to always 'else' after 'if'.

results matching ""

    No results matching ""