if語句可以跟著一個(gè)可選的else語句,else語句塊執(zhí)行時(shí),布爾表達(dá)式是假的。
在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 }
如果布爾表達(dá)式的值為true,那么if代碼塊將被執(zhí)行,否則else塊將被執(zhí)行。
TCL語言使用expr內(nèi)部命令,因此它不是明確地使用expr語句所需的。
#!/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"
當(dāng)上述代碼被編譯和執(zhí)行時(shí),它產(chǎn)生了以下結(jié)果:
a is not less than 20; value of a is : 100
if語句可以跟著一個(gè)可選的else if ... else語句,使用單個(gè)if 測試各種條件if...else if 聲明是非常有用的。
當(dāng)使用if , else if , else語句有幾點(diǎn)要記?。?/p>
一個(gè)if可以有零或一個(gè)else,它必須跟在else if之后。
一個(gè)if語句可以有零到多個(gè)else if,并且它們必須在else之前。
一旦一個(gè) else if 成功,任何剩余else if 或else 不會(huì)再被測試。
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"
當(dāng)上述代碼被編譯和執(zhí)行時(shí),它產(chǎn)生了以下結(jié)果:
None of the values is matching Exact value of a is: 100