Python中的if-else

Python中的if-else决策控制是重要的一种流程控制。顾名思义,Python中的决策允许我们为特定决策运行特定的代码块。在这里,决定指的是特定条件成立的情况下才运行特定的代码块。

在python中,决策由以下语句执行。声明描述

if声明if语句用于测试特定条件。如果条件为真,则执行代码块(if-block)。

if - else声明if-else语句类似于if语句,除了它还提供了要检查的条件的错误情况的代码块。如果if语句中提供的条件为false,则将执行else语句。

Python中的缩进

为了便于编程和实现简单性,python不允许在块级代码中使用括号。在Python中,缩进用于声明块。如果两个语句处于相同的缩进级别,则它们是同一块的一部分。

通常,给出四个空格来缩进语句,这些语句是python中典型的缩进量。

缩进是python语言中最常用的部分,因为它声明了代码块。一个块的所有语句都是在同一级别的缩进中。我们将看到在python中决策和其他内容中实际缩进的情况。

if语句

if语句用于测试特定条件,如果条件为真,则执行称为if-block的代码块。if语句的条件可以是任何有效的逻辑表达式,可以将其计算为true或false。

Python If-else语句

python if else 语句不执行 python if-else_python之if-else

if语句的语法如下。if expression:

statement

例1num = int(input("输入数字?"))

if num%2 == 0:

print("数字是偶数")

输出:输入数字?10

数字是偶数

示例2:打印三个数字中最大的一个的程序。

a = int(input("Enter a? "));
b = int(input("Enter b? "));
c = int(input("Enter c? "));
if a>b and a>c:
print("a is largest");
if b>a and b>c:
print("b is largest");
if c>a and c>b:
print("c is largest");

输出:Enter?100

Enteb?120

Entec?130

c is largest

if-else语句

if-else语句提供了一个else块,该if块与if语句结合使用,该语句在错误的情况下执行。

如果条件为真,则执行if块。否则,执行else块。

Python If-else语句

if-else语句的语法如下。

if condition:
#block of statements
else:
#another block of statements (else-block)

示例1:检查某人是否有资格投票的计划。

age = int (input("Enter your age? "))
if age>=18:
print("You are eligible to vote !!");
else:
print("Sorry! you have to wait !!");

输出:Enter your age?90

You are eligible to vote !!

示例2:用于检查数字是否为偶数的程序。

num = int(input("输入数字?"))
if num%2 == 0:
print("数字是偶数...")
else:
print("数字是奇数...")

输出:输入数字?10

数字是偶数

elif声明

elif语句使我们能够检查多个条件并根据它们之间的真实条件执行特定的语句块。根据我们的需要,我们的程序中可以包含任意数量的elif语句。但是,使用elif是可选的。

elif语句的作用类似于C中的if-else-if梯形图语句。它必须由if语句继承。

python if else 语句不执行 python if-else_if语句_02

elif语句的语法如下。

if expression 1:
# block of statements
elif expression 2:
# block of statements
elif expression 3:
# block of statements
else:
# block of statements

Python If-else语句

python if else 语句不执行 python if-else_缩进_03

例1

number = int(input("Enter the number?"))
if number==10:
print("number is equals to 10")
elif number==50:
print("number is equal to 50");
elif number==100:
print("number is equal to 100");
else:
print("number is not equal to 10, 50 or 100");

输出:Enter the number?15

number is not equal to 10, 50 or 100

例2

marks = int(input("Enter the marks? "))
if marks > 85 and marks <= 100:
print("Congrats ! you scored grade A ...")
elif marks > 60 and marks <= 85:
print("You scored grade B + ...")
elif marks > 40 and marks <= 60:
print("You scored grade B ...")
elif (marks > 30 and marks <= 40):
print("You scored grade C ...")
else:
print("Sorry you are fail ?")