if语句流程图:
if语句是最简单的决策语句。 它用于决定是否执行某个语句或语句块,即如果某个条件为真,则执行语句块,否则不执行.
语法:
if condition:
# Statements to execute if
# condition is true
在此,评估后的条件为真或假。 if语句接受布尔值–如果该值为true,则它将执行其下面的语句块,否则不执行。 我们也可以使用带有括号"('')"的条件。
众所周知,python使用缩进来识别语句块。 因此,将确定if语句下的块,如以下示例所示:
if condition:
statement1
statement2
# Here if the condition is true, if block
# will consider only statement1 to be inside
# its block.
代码演示:
# python program to illustrate If statement
i = 10
if (i > 15):
print ("10 is less than 15")
print ("I am Not in if")
输出:
I am Not in if
由于if语句中判断条件为False。 因此,不执行if语句下面语句。
if- else表达式流程图:
仅if语句告诉我们,如果条件为True,它将执行一个语句块;如果条件为False,则不会执行。 但是如果条件为False,我们想做其他事情怎么办。 这是else语句。 当条件为False时,可以将else语句与if语句一起使用以执行代码块。
语法:
if (condition):
# Executes this block if
# condition is true
else:
# Executes this block if
# condition is false
代码演示:
# python program to illustrate If else statement
#!/usr/bin/python
i = 20;
if (i < 15):
print ("i is smaller than 15")
print ("i'm in if Block")
else:
print ("i is greater than 15")
print ("i'm in else Block")
print ("i'm not in if and not in else Block")
输出结果为:
i is greater than 15
i'm in else Block
i'm not in if and not in else Block
如果if语句中的条件为false,则执行else语句之后的代码块。
if嵌套语句:流程图
Python允许我们在if语句中嵌套if语句。 也就是说,我们可以将if语句放在另一个if语句中。
语法:
if (condition1):
# Executes when condition1 is true
if (condition2):
# Executes when condition2 is true
# if Block is end here
# if Block is end here
代码演示如下:
# python program to illustrate nested If statement
#!/usr/bin/python
i = 10
if (i == 10):
# First if statement
if (i < 15):
print ("i is smaller than 15")
# Nested - if statement
# Will only be executed if statement above
# it is true
if (i < 12):
print ("i is smaller than 12 too")
else:
print ("i is greater than 15")
输出结果为:
i is smaller than 15
i is smaller than 12 too
if-elif-else表达式:
在这里,用户可以在多个选项中进行选择。 if语句从上至下执行。 一旦控制if的条件之一为True,则与if关联的语句被执行,其余语句将被忽略。 如果没有一个条件为True,则将执行最终的else语句。
语法如下:
if (condition):
statement
elif (condition):
statement
.
.
else:
statement
流程图:
代码演示如下:
# Python program to illustrate if-elif-else ladder
#!/usr/bin/python
i = 20
if (i == 10):
print ("i is 10")
elif (i == 15):
print ("i is 15")
elif (i == 20):
print ("i is 20")
else:
print ("i is not present")
输出结果为:
i is 20
好了,有点小复杂,没有理解的小伙伴多看几遍,一个知识点理解不了的话就多看几遍,多跑几遍,熟悉了就记住了,我刚开始也是这样的。
希望对大家有用。
编程学习愉快哈