Tcl 中的 if...else语句函数

首页 / Tcl/Tk入门教程 / Tcl 中的 if...else语句函数

if 语句后可以跟可选的 else 语句,该语句在布尔表达式为false时执行。

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
}

if...else - 流程图

If Else Statement

if...else 示例

#!/usr/bin/tclsh

set a 100

#检查布尔条件
if {$a < 20 } {
   #如果条件为真,则打印以下内容
   puts "a is less than 20"
} else {
   #如果条件为假,则打印以下内容
   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 - 语法

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 
} 

if ... else if ... else - 示例

#!/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

祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)

技术教程推荐

黄勇的OKR实战笔记 -〔黄勇〕

研发效率破局之道 -〔葛俊〕

苏杰的产品创新课 -〔苏杰〕

操作系统实战45讲 -〔彭东〕

容量保障核心技术与实战 -〔吴骏龙〕

性能优化高手课 -〔尉刚强〕

JavaScript进阶实战课 -〔石川〕

AI大模型之美 -〔徐文浩〕

AI大模型系统实战 -〔Tyler〕

好记忆不如烂笔头。留下您的足迹吧 :)