Conditional Statements
Conditional Statements, also known as if-else
statements, are used to execute a block of code based on a condition.
Conditions are represented by boolean expressions, which we briefly explored in the second section's "Booleans" chapter. To recall, a boolean expression is a combination of logical and/or comparison operations and may or may not include other operators.
A conditional statement uses if
, else if
, and else
keywords. The syntax for writing a simple conditional statement is as follows:
If the value of the 'expression' in the parentheses is true
, the code enclosed in the curly brackets is executed. Otherwise, it is ignored. Here is an example:
index.go
Since the expression 3 < 4
evaluates to true
, the code inside the curly braces is executed. If we modify the expression to make it false
, the Println
statement won't be executed.
index.go
The following diagram shows the execution of the if
-condition:
You can use the else
keyword to specify code that should be executed when the condition is not met. The else
statement does not require a boolean expression.
index.go
Here's how the execution flow unfolds when we use else
in the condition:
Все було зрозуміло?
Зміст курсу
Introduction to GoLang
Introduction to GoLang
Conditional Statements
Conditional Statements, also known as if-else
statements, are used to execute a block of code based on a condition.
Conditions are represented by boolean expressions, which we briefly explored in the second section's "Booleans" chapter. To recall, a boolean expression is a combination of logical and/or comparison operations and may or may not include other operators.
A conditional statement uses if
, else if
, and else
keywords. The syntax for writing a simple conditional statement is as follows:
If the value of the 'expression' in the parentheses is true
, the code enclosed in the curly brackets is executed. Otherwise, it is ignored. Here is an example:
index.go
Since the expression 3 < 4
evaluates to true
, the code inside the curly braces is executed. If we modify the expression to make it false
, the Println
statement won't be executed.
index.go
The following diagram shows the execution of the if
-condition:
You can use the else
keyword to specify code that should be executed when the condition is not met. The else
statement does not require a boolean expression.
index.go
Here's how the execution flow unfolds when we use else
in the condition:
Все було зрозуміло?