Tcl If else 语句
一个 if 语句可以跟着一个可选的 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 语句。
流程图
示例
#!/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…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