Tcl if...else語句


if語句可以跟著一個可選的else語句,else語句塊執行時,布林表示式是假的。

語法

在Tcl語言的if ... else語句的語法是:

if {boolean_expression} {
  # statement(s) will execute if the boolean expression is true 
} else {
  # statement(s) will execute if the boolean expression is false
}

如果布林表示式的值為true,那麼if程式碼塊將被執行,否則else塊將被執行。

TCL語言使用expr內部命令,因此它不是明確地使用expr語句所需的。

流程圖

If Else Statement

範例

#!/usr/bin/tclsh

set a 100

#check the boolean condition 
if {$a < 20 } {
   #if condition is true then print the following 
   puts "a is less than 20"
} else {
   #if condition is false then print the following 
   puts "a is not less than 20"
}
puts "value of a is : $a"

當上述程式碼被編譯和執行時,它產生了以下結果:

a is not less than 20;
value of a is : 100

if...else if...else 語句

if語句可以跟著一個可選的else if ... else語句,使用單個if 測試各種條件if...else if 宣告是非常有用的。

當使用if , else if , else語句有幾點要記住:

  • 一個if可以有零或一個else,它必須跟在else if之後。

  • 一個if語句可以有零到多個else if,並且它們必須在else之前。

  • 一旦一個 else if 成功,任何剩餘else if 或else 不會再被測試。

語法

Tcl語言的 if...else if...else語句的語法是:

if {boolean_expression 1} {
   # Executes when the boolean expression 1 is true
} elseif {boolean_expression 2} {
   # Executes when the boolean expression 2 is true 
} elseif {boolean_expression 3} {
   # Executes when the boolean expression 3 is true 
} else {
   # executes when the none of the above condition is true 
}

範例

#!/usr/bin/tclsh

set a 100

#check the boolean condition
if { $a == 10 } {
   # if condition is true then print the following 
   puts "Value of a is 10"
} elseif { $a == 20 } {
   # if else if condition is true 
   puts "Value of a is 20"
} elseif { $a == 30 } {
   # if else if condition is true 
   puts "Value of a is 30"
} else {
   # if none of the conditions is true 
   puts "None of the values is matching"
}

puts "Exact value of a is: $a"

當上述程式碼被編譯和執行時,它產生了以下結果:

None of the values is matching
Exact value of a is: 100