Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Apprendre Conditional Statements | Section
Practice
Projects
Quizzes & Challenges
Quiz
Challenges
/
Getting Started with Go

bookConditional Statements

Glissez pour afficher le menu

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 expression {
   // code to execute
}

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

index.go

copy
12345678910
package main import "fmt" func main() { fmt.Println("Before if-condition") if (3 < 4) { fmt.Println("3 is greater than 4") } fmt.Println("After if-condition") }

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

index.go

copy
12345678910
package main import "fmt" func main() { fmt.Println("Before if-condition") if (3 > 4) { fmt.Println("3 is greater than 4") } fmt.Println("After if-condition") }

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

index.go

copy
1234567891011
package main import "fmt" func main() { var value int = 70 if (value <= 50) { fmt.Println("The value is less or equal to 50") } else { fmt.Println("The value is greater than 50") } }

Here's how the execution flow unfolds when we use else in the condition:

question mark

Which keyword is used for writing an if statement in Go?

Select the correct answer

Tout était clair ?

Comment pouvons-nous l'améliorer ?

Merci pour vos commentaires !

Section 1. Chapitre 20

Demandez à l'IA

expand

Demandez à l'IA

ChatGPT

Posez n'importe quelle question ou essayez l'une des questions suggérées pour commencer notre discussion

Section 1. Chapitre 20
some-alt