返回

If-Then 语句:揭秘编程中的条件执行

Office技巧

输入
If-Then语句

输出

If-Then 语句,又称条件语句,是编程语言中一种基本控制结构,用于根据给定条件执行不同的代码块。它允许程序员在代码中加入逻辑判断,使程序能够根据不同的情况做出不同的反应。

If-Then 语句的基本语法如下:

if (condition) {
  // 如果条件为真,执行此代码块
} else {
  // 如果条件为假,执行此代码块
}

其中,condition 是一个布尔表达式,用来判断条件是否为真。如果 condition 为真,则执行第一个代码块;如果 condition 为假,则执行第二个代码块。

举个例子,以下代码使用 If-Then 语句来判断一个数字是否大于 10:

number = int(input("Enter a number: "))

if number > 10:
  print("The number is greater than 10.")
else:
  print("The number is less than or equal to 10.")

当用户输入一个数字后,程序会将该数字与 10 进行比较。如果该数字大于 10,则程序会输出“The number is greater than 10.”;否则,程序会输出“The number is less than or equal to 10.”。

If-Then 语句还可以用于嵌套,即在一个 If-Then 语句中包含另一个 If-Then 语句。这允许程序员根据多个条件来控制程序执行流程。

以下代码使用嵌套 If-Then 语句来判断一个数字是否大于 10,并且是否为偶数:

number = int(input("Enter a number: "))

if number > 10:
  if number % 2 == 0:
    print("The number is greater than 10 and even.")
  else:
    print("The number is greater than 10 and odd.")
else:
  print("The number is less than or equal to 10.")

当用户输入一个数字后,程序会先判断该数字是否大于 10。如果该数字大于 10,则程序会继续判断该数字是否为偶数。如果该数字为偶数,则程序会输出“The number is greater than 10 and even.”;否则,程序会输出“The number is greater than 10 and odd.”。如果该数字不大于 10,则程序会输出“The number is less than or equal to 10.”。

If-Then 语句是编程语言中一种非常重要的控制结构,它可以帮助程序员根据不同的情况执行不同的代码块,从而使程序更加灵活和智能。