15 KiB
Python 中的if-else语句
原文:https://overiq.com/python-101/if-else-statements-in-python/
最后更新于 2020 年 9 月 21 日
到目前为止,我们编写的程序执行得非常有序。现实世界中的程序不是这样运行的。有时,我们只希望在满足特定条件时执行一组语句。为了处理这些情况,编程语言提供了一些称为控制语句的特殊语句。除了控制程序的流程,当某些条件为真时,我们还使用控制语句来循环或跳过语句。
控制语句有以下几种类型:
- 如果语句
- if-else 语句
- if-elif-else 语句
- while 循环
- for 循环
- break 语句
- 连续语句
在本课中,我们将讨论前三个控制语句。
如果语句
if 语句的语法如下:
语法:
if condition:
<indented statement 1>
<indented statement 2>
<non-indented statement>
语句的第一行即if condition:被称为 if 子句,condition是一个布尔表达式,其计算结果为True或False。在下一行中,我们有一组语句。一个块只是一个或多个语句的集合。当一个语句块后跟 if 子句时,它被称为 if 块。请注意,if 块中的每个语句在 if 关键字右侧缩进相同的量。许多语言,如 C、C++、Java、PHP,使用花括号({})来确定块的开始和结束,但是 Python 使用缩进。if 块中的每个语句都必须缩进相同数量的空格。否则,您会得到语法错误。Python 文档建议将块中的每个语句缩进 4 个空格。在本课程的所有课程中,我们都使用这一建议。
工作原理:
if 语句执行时,测试条件。如果条件为真,则执行 If 块中的所有语句。另一方面,如果条件为假,则跳过 if 块中的所有语句。
没有缩进的 if 子句后面的语句不属于 if 块。例如,<non-indented statement>不是 if 块的一部分,因此,不管 if 子句中的条件是真还是假,它都会一直执行。
这里有一个例子:
蟒蛇 101/章节-09/if_statement.py
number = int(input("Enter a number: "))
if number > 10:
print("Number is greater than 10")
首次运行输出:
Enter a number: 100
Number is greater than 10
第二次运行输出:
Enter a number: 5
请注意,在条件失败时的第二次运行中,if 块中的语句被跳过。在这个例子中,if 块只包含一个语句,但是您可以有任意数量的语句,只要记住适当地缩进它们。
现在考虑以下代码:
python 101/章节-09/if_statement_block.py
number = int(input("Enter a number: "))
if number > 10:
print("statement 1")
print("statement 2")
print("statement 3")
print("Executes every time you run the program")
print("Program ends here")
首次运行输出:
Enter a number: 45
statement 1
statement 2
statement 3
Executes every time you run the program
Program ends here
第二次运行输出:
Enter a number: 4
Executes every time you run the program
Program ends here
在这个程序中需要注意的重要一点是,只有第 3、4 和 5 行的语句属于 if 块。因此,第 3、4 和 5 行中的语句只有在 if 条件为真时才会执行,而第 6 和 7 行中的语句无论如何都会执行。
当您在 Python shell 中键入控制语句时,它的响应有些不同。回想一下,要将一条语句拆分成多行,我们使用行延续运算符(\)。控制语句不是这种情况,Python 解释器会在您按下 enter 键后立即自动将您置于多行模式。考虑以下示例:
>>>
>>> n = 100
>>> if n > 10:
...
请注意,在按回车键后跟 if 子句后,Shell 提示从>>>变为...。Python shell 显示...对于多行语句,它只是意味着您开始的语句尚未完成。
要完成 if 语句,请向 if 块添加如下语句:
>>>
>>> n = 100
>>> if n > 10:
... print("n is greater than 10")
...
Python shell 不会自动缩进您的代码,您必须自己缩进。当您在块中键入完语句后,按两次回车键执行该语句,您将返回到正常的提示字符串。
>>>
>>> n = 100
>>> if n > 10:
... print("n is greater than 10")
...
n is greater than 10
>>>
如果条件为假,我们到目前为止编写的程序会突然结束,而不会向用户显示任何响应。大多数情况下,即使条件为假,我们也希望向用户显示响应。我们可以使用 if-else 语句轻松做到这一点
if-else 语句
if-else 语句在条件为真时执行一组语句,在条件为假时执行另一组语句。这样,if-else 语句允许我们遵循两个行动过程。if-else 语句的语法如下:
语法:
if condition:
# if block
statement 1
statement 2
and so on
else:
# else block
statement 3
statement 4
and so on:
工作原理:
当 if-else 语句执行时,如果条件被评估为True,则测试条件,然后执行 if 块中的语句。但是,如果条件是False,则执行 else 块中的语句。
这里有一个例子:
例 1 :计算圆的面积和周长的程序
蟒蛇 101/第-09 章/计算 _ 圆 _ 面积 _ 周长. py
radius = int(input("Enter radius: "))
if radius >= 0:
print("Circumference = ", 2 * 3.14 * radius)
print("Area = ", 3.14 * radius ** 2 )
else:
print("Please enter a positive number")
首次运行输出:
Enter radius: 4
Circumference = 25.12
Area = 50.24
第二次运行输出:
Enter radius: -12
Please enter a positive number
现在我们的程序向用户显示了一个适当的响应,即使条件是假的,这也是我们想要的。
在 if-else 语句中,始终确保 if 和 else 子句正确对齐。否则将会引发语法错误。例如:
python 101/章节-09/if _ and _ else _ not _ aligned . py
radius = int(input("Enter radius: "))
if radius >= 0:
print("Circumference = ", 2 * 3.14 * radius)
print("Area = ", 3.14 * radius ** 2 )
else:
print("Please enter a positive number")
尝试运行上面的程序,您会得到如下语法错误:
q@vm:~/python101/Chapter-09$ python3 if_and_else_not_aligned.py
File "if_and_else_not_aligned.py", line 6
else:
^
SyntaxError: invalid syntax
q@vm:~/python101/Chapter-06$
要解决该问题,请将 if 和 else 子句垂直对齐,如下所示:
radius = int(input("Enter radius: "))
if radius >= 0:
print("Circumference = ", 2 * 3.14 * radius)
print("Area = ", 3.14 * radius ** 2 )
else:
print("Please enter a positive number")
下面是另一个例子:
例 2 :检查用户输入的密码的程序
蟒蛇 101/第-09 章/秘密 _ 世界. py
password = input("Enter a password: ")
if password == "sshh":
print("Welcome to the Secret World")
else:
print("You are not allowed here")
首次运行输出:
Enter a password: sshh
Welcome to the Secret World
第二次运行输出:
Enter a password: ww
You are not allowed here
嵌套的 if 和 if-else 语句
我们还可以在另一个 if 或 if-else 语句中编写 if 或 if-else 语句。这可以通过一些例子更好地解释:
另一个 if 语句中的 if 语句。
例 1: 检查学生是否符合贷款条件的程序
python 101/章节-09/nested_if_statement.py
gre_score = int(input("Enter your GRE score: "))
per_grad = int(input("Enter percent secured in graduation: "))
if per_grad > 70:
# outer if block
if gre_score > 150:
# inner if block
print("Congratulations you are eligible for loan")
else:
print("Sorry, you are not eligible for loan")
这里我们在另一个 if 语句中写了一个 if 语句。内部 if 语句被称为嵌套 if 语句。在这种情况下,内部 if 语句属于外部 if 块,而内部 if 块只有一个打印"Congratulations you are eligible for loan"的语句。
工作原理:
首先评估外中频条件,即per_grad > 70,如果是True,那么程序的控制进入外中频模块。在外如果块gre_score > 150条件被测试。如果是True,则"Congratulations you are eligible for loan"被打印到控制台。如果是False,则控制从 if-else 语句中出来,执行其后的语句,并且不打印任何内容。
另一方面,如果外部 if 条件被评估为False,则跳过外部 if 块内部语句的执行,控制跳转到 else(第 9 行)块以执行其内部语句。
首次运行输出:
Enter your GRE score: 160
Enter percent secured in graduation: 75
Congratulations you are eligible for loan
第二次运行输出:
Enter your GRE score: 160
Enter percent secured in graduation: 60
Sorry, you are not eligible for loan
这个程序有一个小问题。再次运行程序,输入小于 T1 的 T0 和大于 T3 的 T2,如下所示:
输出:
Enter your GRE score: 140
Enter percent secured in graduation: 80
如您所见,程序不输出任何内容。这是因为我们的嵌套 if 语句没有 else 子句。在下一个示例中,我们将在嵌套的 if 语句中添加一个 else 子句。
例 2: 另一个 if 语句内部的 if-else 语句。
python 101/章节-09/nested _ if _ else _ statement . py
gre_score = int(input("Enter your GRE score: "))
per_grad = int(input("Enter percent secured in graduation: "))
if per_grad > 70:
if gre_score > 150:
print("Congratulations you are eligible for loan.")
else:
print("Your GRE score is no good enough. You should retake the exam.")
else:
print("Sorry, you are not eligible for loan.")
输出:
Enter your GRE score: 140
Enter percent secured in graduation: 80
Your GRE score is no good enough. You should retake the exam.
工作原理:
这个程序的工作原理和上面完全一样,唯一的区别是我们在这里添加了一个 else 子句,对应于嵌套的 if 语句。因此,如果你输入的 GRE 分数小于 150,程序会打印“你的 GRE 分数不够好。你应该重考。”而不是什么都不打印。
编写嵌套的 if 或 if-else 语句时,请始终记住正确缩进所有语句。否则你会得到一个语法错误。
else 子句中的 if-else 语句。
示例 3: 根据输入的分数确定学生成绩的程序。
蟒蛇 101/第-09 章/测试 _ 多重 _ 条件. py
score = int(input("Enter your marks: "))
if score >= 90:
print("Excellent ! Your grade is A")
else:
if score >= 80:
print("Great ! Your grade is B")
else:
if score >= 70:
print("Good ! Your grade is C")
else:
if score >= 60:
print("Your grade is D. You should work hard on you subjects.")
else:
print("You failed in the exam")
首次运行输出:
Enter your marks: 92
Excellent ! Your grade is A
第二次运行输出:
Enter your marks: 75
Good ! Your grade is C
第三次运行输出:
Enter your marks: 56
You failed in the exam
工作原理:
当程序控制进入 if-else 语句时,测试第 3 行的条件(score >= 90)。如果条件为True,控制台上会打印"Excellent ! Your grade is A"。如果条件为假,控制跳转到第 5 行的 else 子句,然后测试条件score >= 80(第 6 行)。如果是真的,那么"Great ! Your grade is B"被打印到控制台。否则,程序控制跳转到第 8 行的 else 子句。同样,我们有一个带有嵌套 if-else 语句的 else 块。测试条件(score >= 70)。如果为真,则"Good ! Your grade is C"被打印到控制台。否则,控制再次跳到第 11 行的 else 块。最后,测试条件(score >= 60),如果是True,则"Your grade is D. You should work hard on you subjects."被打印到控制台。另一方面,如果为假,则将"You failed the exam"打印到控制台。此时,控件从外部 if-else 语句中出来,执行其后的语句。
虽然嵌套的 if-else 语句允许我们测试多个条件,但是它们的读写相当复杂。我们可以使用 if-elif-else 语句使上面的程序更加易读和简单。
if-elif-else 语句
If-elif-else 语句是 if-else 语句的另一种变体,它允许我们轻松地测试多个条件,而不是编写嵌套的 if-else 语句。if-elif-else 语句的语法如下:
语法:
if condition_1:
# if block
statement
statement
more statement
elif condition_2:
# 1st elif block
statement
statement
more statement
elif condition_3:
# 2nd elif block
statement
statement
more statement
...
else
statement
statement
more statement
...表示你,表示你可以根据需要写任意多的 elif 子句。
工作原理:
当 if-elif-else 语句执行时,首先测试condition_1。如果条件为真,则执行 If 块中的语句。结构的其余部分中的条件和语句被跳过,控制从 if-elif-else 语句中出来,执行其后的语句。
如果condition_1为假,程序控制跳转到下一个 elif 子句,并测试condition_2。如果condition_2为真,则执行第一个 elif 块中的语句。if-elif-else 结构的其余部分中的条件和语句被跳过,控制权从 if-elif-语句中出来,执行其后的语句。
这个过程一直重复,直到发现 elif 子句为真。如果没有发现 elif 子句为真,那么最后执行 else 块中的语句块。
让我们使用 if-elif-语句重写上面的程序。
蟒蛇 101/章节-09/if _ elif _ else _ statement . py
score = int(input("Enter your marks: "))
if score >= 90:
print("Excellent! Your grade is A")
elif score >= 80:
print("Great! Your grade is B")
elif score >= 70:
print("Good! Your grade is C")
elif score >= 60:
print("Your grade is D. You should work hard on you studies.")
else:
print("You failed in the exam")
首次运行输出:
Enter your marks: 78
Good ! Your grade is C
第二次运行输出:
Enter your marks: 91
Excellent! Your grade is A
第三次运行输出:
Enter your marks: 55
You failed in the exam
正如你所看到的,上面的程序很容易阅读和理解,不像它的嵌套等价物。