python之if-else_Python中的if-else

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语句

9572e80878879fd5100b14da2e1be397.png

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语句继承。

0469aeb635c58b3a0ec1d3516a542ca1.png

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语句

7f008f38f2f6853fe0d1fcb60e7a9915.png

例1number = 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

例2marks = 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 ?")

  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值