[ASP.NET WebForm] #2 條件式語句基本介紹、範例 - antqtech/KM GitHub Wiki

本篇重點:

  • 條件式語句
  • 範例練習

條件式語句介紹

條件式語句是程式中用來根據條件的真假執行不同程式碼的語句。它允許程式根據特定條件的結果,選擇性地執行或跳過程式碼的不同部分。

常見的條件式語句有:

  1. If 語句:根據條件的真假執行不同的程式碼塊。如果條件為真,則執行 If 區塊中的程式碼;如果條件為假,則可以選擇性地執行 Else 區塊中的程式碼。
  2. Else 語句:通常與 if 語句一起使用,用於在條件為假時執行特定的程式碼塊。
  3. Else if 語句:Else if 語句(在某些程式語言中也稱為 elif)用於在多個條件之間進行選擇。如果前面的 If 或 Else if 條件為假,則評估下一個 Else if 條件,直到找到一個條件為真或達到最後的 Else 塊。

這些條件式語句可根據不同程式語言的語法進行使用。可用於控制程式流程、執行特定的程式邏輯,以及根據不同的條件做出不同的處理或選擇。

範例練習

這篇會教大家如何寫條件式語句,學會基本的寫法後就可以自己做更多變化~~~~

基本語法

If condition Then
    ' 如果條件為真,執行這裡的程式碼
ElseIf condition2 Then
    ' 如果條件2為真,執行這裡的程式碼
Else
    ' 如果以上條件都不滿足,執行這裡的程式碼
End If

使用範例

  1. 基本的條件判斷
'宣告一個變數 5
Dim num As Integer = 5  

If num > 10 Then 
    '如果這個變數 > 10,執行以下程式
    Label1.Text = "Number is greater than 10" 
Else
    '在不滿足以上條件的形況下,執行以下程式
    Label1.Text = "Number is less than or equal to 10"
End If
  1. 多個條件判斷
'宣告一個變數 5
Dim num As Integer = 5

If num > 10 Then
    '如果這個變數 > 10,執行以下程式
    Label1.Text = "Number is greater than 10"
ElseIf num > 5 Then
    '在不滿足以上條件的形況下,如果這個變數 > 5,執行以下程式
    Label1.Text = "Number is greater than 5"
Else
    '在不滿足以上條件的形況下,執行以下程式
    Label1.Text = "Number is 5 or less"
End If
  1. 巢狀的 if 句式
'宣告一個變數 7
Dim num As Integer = 7

If num > 5 Then
    If num < 10 Then
        Label1.Text = "Number is between 5 and 10"
    Else
        Label1.Text = "Number is greater than or equal to 10"
    End If
Else
    Label1.Text = "Number is less than or equal to 5"
End If

  1. 使用邏輯運算符號
Dim num As Integer = 7

If num > 5 And num < 10 Then
    Label1.Text = "Number is between 5 and 10"
Else
    Label1.Text = "Number is not between 5 and 10"
End If