个性化阅读
专注于IT技术分析

Python IF,ELIF和ELSE语句

本文概述

Python IF,ELIF和ELSE语句1

用任何语言编写代码时, 你都必须控制程序的流程。通常是在涉及决策的情况下-如果满足条件, 你将要执行特定的代码行, 如果不满足, 则要执行另一组代码。在Python中, 你可以使用if, elif和else语句来实现此目的。在本教程中, 你将使用一个示例来学习简单的if语句, 然后逐步进入if-else然后是if-elif-else语句。你还将学习有关嵌套的内容, 并查看嵌套的if示例。让我们开始吧….

简单的if语句

这是条件语句的最简单示例。语法为:

如果(条件):

缩进语句块

只要条件为TRUE, 将在冒号(:)之后缩进相同的行数。

Python IF,ELIF和ELSE语句2

来源:Programiz的python

例如, 假设你正在记录某门课程的分数。总分为100分, 其中理论工作得分50分, 实践得分50分。如果分数超过100, 则要显示错误消息或警告。

score_theory = 40
score_practical = 45
if(score_theory + score_practical > 100):
    print("Invalid score. Please check the input.")

冒号(:)很重要, 因为它将条件与条件评估后要执行的语句分开。对于只有一个语句且不使用方括号()的语句, 这尤其重要。例如:

score_theory = 40
score_practical = 45
if score_theory + score_practical > 100: # End of condition
    print("Invalid score. Please check the input.")

上面的if语句检查’if’条件并确定(40 + 45 = 85)> 100的语句为FALSE, 因此不会打印警告。让我们将语句设为FALSE, 看看会发生什么:

score_theory = 50
score_practical = 55
if(score_theory + score_practical >= 100):
    print("Invalid score. Please check the input.")
Invalid score. Please check the input.

假设你想更进一步, 并在总分实际上在该范围内(即小于100)时显示一条语句。这是if-else语句会有所帮助的时候。

一次测试:if-else语句

if-else语句用于编码的方式与使用英语的方式相同。 if-else语句的语法为:

如果(条件):

条件为TRUE时的缩进语句块

其他:

条件为FALSE时的缩进语句块

Python IF,ELIF和ELSE语句3

来源:Programiz的python

让我们尝试从上面的代码开始工作, 并重新定义问题:当记录某门课程的分数时, 你希望将理论部分和实践部分的分数加起来以获得总分数。如果总分小于100-你想显示”分数还可以”消息, 如果不是, 则像以前一样显示警告。

score_theory = 40
score_practical = 45
if(score_theory + score_practical > 100):
    print("Please check the input. Score exceeds total possible score.")
else:
    print("Score validated. Your total is: ", score_theory + score_practical)
Score validated. Your total is:  85

提示:如果仅要执行的一行代码而不是该条件之后的代码中的多行, 则可以将其全部放在同一行中。这不是规则, 而只是编码人员之间的常见做法。使用这种样式从上面重写代码:

score_theory = 40
score_practical = 45
# Single statement: if(condition): Statement for when condition is true
if (score_theory + score_practical > 100): print("Please check the input. Score exceeds total possible score.")
# Single statement: if(condition): Statement for when condition is false
else: print("Score validated. Your total is: ", score_theory + score_practical)
Score validated. Your total is:  85

现在想象一种情况, 其中一个分数超过50, 但总分仍然小于100。那么你认为会发生什么呢?

score_theory = 60
score_practical = 40
if(score_theory + score_practical > 100):
    print("Please check the input. Score exceeds total possible score.")
else:
    print("Score validated. Your total is: ", score_theory + score_practical)
Score validated. Your total is:  100

这是错误的, 因为你知道理论或实践中单个分数的最大限制不应超过50。如何在代码中体现这一点? ans:if-elif-else语句。

多种测试:if-elif-else语句

让我们来解决目前存在的问题, 并在跳入代码之前尝试用单词将其构筑起来。

步骤1.输入两个分数:score_theory和score_practical

步骤2.检查所有分数均未超过最大可能分数50。这也解决了总分数不超过10)的问题。如果任何一个大于50-显示警告并退出。

  • 2.1检查score_theory
  • 2.2检查score_practical

步骤3.如果两者均未超过分数, 则显示”分数还可以”并退出。

# Step 1
score_theory = 60
score_practical = 20

if(score_theory > 50):
    print("Please check the input score for 'Theory'.") # Step 2.1
elif(score_practical > 50):
    print("Please check the input score for 'Practical'.")  # Step 2.2
else:
    print("Score validated. Your total is: ", score_theory + score_practical) # Step 3
Please check the input score for 'Theory'.

if-else-if语句后面的语法是:

if(Condition1):

Condition1的缩进语句块

ELIF(条件2):

Condition2的缩进语句块

其他:

如果上述所有条件检查均失败, 则备用语句块

Python IF,ELIF和ELSE语句4

来源:Programiz的python

通过一种精心设计的方式来查看if-elif-else语句的效果, 就像if-else语句将其编写如下所示:

score_theory = 60
score_practical = 20

if(score_theory > 50):
    print("Please check the input score for 'Theory'.")
else:
    if(score_practical > 50):
        print("Please check the input score for 'Practical'.")  
    else:
        print("Score validated. Your total is: ", score_theory + score_practical)
Please check the input score for 'Theory'.

elif语句实际上使编写代码更容易。想象一下, 如果问题语句变得更加复杂, 那么跟踪另一个if语句中的每个if-else语句就很容易成为噩梦!

让我们在同一示例上做更多的工作。现在, 假设你想跟踪多个课程, 例如:”科学”和”英语”。两者的总分仍是相同的, 即100。但是, 对于科学, 理论和实践的细分是50-50, 而对于英语, 则是60-40。你还能使用上面的格式吗?

是!你可以使用嵌套if语句的概念轻松完成此操作

嵌套if语句

当你在另一个if语句中包含一个if语句时, 这在编程世界中称为嵌套。它不一定总是简单的if语句, 但是你可以使用if, if-else甚至if-elif-else语句的组合概念来形成更复杂的结构。

让我们为上面讨论的示例编写代码:

coursework = "English"
score_theory = 53
score_practical = 35

if(coursework == "Science" or coursework == "science"):
    if(score_theory > 50):
        print("Please check the input score for 'Science: Theory'.")
    elif(score_practical > 50):
            print("Please check the input score for 'Science: Practical'.")  
    else:
        print("Score validated for Science. Your total is: ", score_theory + score_practical)             
elif(coursework == "English" or coursework == "english"):
    if(score_theory > 60):
        print("Please check the input score for 'English: Theory'.")
    elif(score_practical > 40):
            print("Please check the input score for 'English: Practical'.")  
    else:
        print("Score validated for English. Your total is: ", score_theory + score_practical)
else: print("Coursework not recognised. Please enter score for either Science or English.")
Score validated for English. Your total is:  88

请注意上面的代码中使用或?它是用来评估”科学”和”科学”作为相同的课程, “英语”和”英语”也是如此。可以使用布尔语句(例如or), 并将多个条件组合在一起。但是, 你必须小心理解此类组合语句的布尔输出, 才能完全实现程序的控制流。

我们可以重写上面的代码以检查同一条语句中的分数, 但是, 这确实使代码难以阅读并且有时难以调试这些语句。

coursework = "English"
score_theory = 53
score_practical = 78

if(coursework == "Science" or coursework == "science"):
    if(score_theory > 50 or score_practical > 50):
        # Can't distinguish the error in Science: theory or Science: Practical
        print("Please check the input score for Science.")
    else: print("Score validated for Science. Your total is: ", score_theory + score_practical)             
elif(coursework == "English" or coursework == "english"):
    if(score_theory > 60 or score_practical > 40):
        # Can't distinguish the error in English: theory or English: Practical
        print("Please check the input score for English.")
    else: print("Score validated for English. Your total is: ", score_theory + score_practical)
else: print("Coursework not recognised. Please enter score for either Science or English.")
Please check the input score for English.

瞧!

在本教程中, 你解决了Python中可用的主要控制流机制之一。你已经在多个级别上使用了示例, 以查看实际的if语句的变化。要了解有关Python的更多信息, 请查看srcmini的Python数据科学入门课程。

赞(0)
未经允许不得转载:srcmini » Python IF,ELIF和ELSE语句

评论 抢沙发

评论前必须登录!