Python初级教程

Python初级教程(10): if...else 语句

2019-10-19  本文已影响0人  R语言和Python学堂

有时我们想在满足特定条件的情况下才执行代码,这时我们需要做决策。Python中的if…else语句就是用于做决策。

在本文中,您将学习使用不同形式的if...else语句来做决策。常见的形式有:

下面结合例子来看下它们的详细用法:

1. if 语句

其语法为:

if test expression:
    statement(s)

流程图为:

图片.png

来看个例子:

num = 3
if num > 0:
    print(num, "is a positive number.")
print("This is always printed.")

num = -1
if num > 0:
    print(num, "is a positive number.")
print("This is also always printed.")

输出为:

3 is a positive number.
This is always printed.
This is also always printed.

在上面的例子中,num > 0是个测试表达式(test expression),只有它的值为Trueif中的语句才会执行。

当变量num的值为3时,num > 0的值为Trueif中的print(num, "is a positive number.")会执行。

当变量num的值为-1时,num > 0的值为Falseif中的print(num, "is a positive number.")将不会执行,直接跳过。

由于print("This is always printed.")print("This is also always printed.")语句(未缩进)位于if代码块之外,因此无论测试表达式如何,它们都将执行。

2. if...else 语句

其语法为:

if test expression:
    Body of if
else:
    Body of else

流程图为:

图片.png
# Program checks if the number is positive or negative
# And displays an appropriate message

num = 3

# Try these two variations as well. 
# num = -5
# num = 0

if num >= 0:
    print(num, "is a positive number or zero")
else:
    print(num, "is a negative number")

输出为:

3 is a positive number or zero

在上面的例子中,当num = 3时,测试表达式num >= 0True,执行if主体,跳过else主体。

如果num = -5,测试表达式为False,执行else的主体,跳过if的主体。

如果num = 0,测试表达式为True,执行if的主体,跳过else的主体。

3. if...elif...else 语句

其语法为:

if test expression:
    Body of if
elif test expression:
    Body of elif
else: 
    Body of else

流程图为:

图片.png

看个例子:

# In this program, 
# we check if the number is positive or
# negative or zero and 
# display an appropriate message

num = 3.4

# Try these two variations as well:
# num = 0
# num = -4.5

if num > 0:
    print("Positive number")
elif num == 0:
    print("Zero")
else:
    print("Negative number")

输出为:

Positive number

当变量num为正数时,打印"Positive number"。

如果num等于0,则打印"Zero"。

如果num为负数,则打印"Negative number"。

4. 嵌套的 if...else语句

我们可以在if ... elif ... else语句中包含另一个if ... elif ... else语句,称为嵌套。缩进是弄清楚嵌套级别的唯一方法。

来看个例子:

# In this program, we input a number
# check if the number is positive or
# negative or zero and display
# an appropriate message
# This time we use nested if
num = float(input("Enter a number: "))
if num >= 0:
    if num == 0:
        print("Zero")
    else:
        print("Positive number")
else:
    print("Negative number")

输出为:

Enter a number: 4
Positive number

或输出为:

Enter a number: -2
Negative number

或输出为:

Enter a number: 0
Zero

今天的内容就讲到这。


感谢您的阅读!想了解更多有关R语言技巧,请关注我的微信公众号“R语言和Python学堂”,我将定期更新相关文章。

上一篇 下一篇

猜你喜欢

热点阅读