Python之if

对于if,文档是这么描述的:

Any object can be tested for truth value, for use in
an if or while condition or as operand of the Boolean
operations below. The following values are considered false:
1. None
2. False
3. zero of any numeric type, for example, 0, 0.0, 0j.
4. any empty sequence, for example, ”, (), [].
5. any empty mapping, for example, {}.
6. instances of user-defined classes, if the class defines
a bool() or len() method, when that method
returns the integer zero or bool value False.

All other values are considered true — so objects of many types are always true.

Operations and built-in functions
that have a Boolean result always return 0 or False for false and 1 or True for true,
unless otherwise stated.
(Important exception: the Boolean operations or and and always return one of their operands.)

基本语法

if 条件:
    处理代码

if 条件:
    处理代码
else:
    处理代码

if 条件:
    处理代码
elif 条件:
    处理代码
elif 条件:
    处理代码
……
else:
    处理代码

if的基本语法就以上三种。

例子

下面用简单的例子来说明。首先是第一种结构,只有一个if:

if people_number > dogs_number:
    print("people are more than dogs")

运行结果如下:
这里写图片描述
第二种结构是最常见的结构:

#####logic#####
people_number = 20
dogs_number = 10
cats_number = 5

if people_number > dogs_number:
    print("people are more than dogs")
else:
    print("people are less than dogs")    

if people_number > cats_number:
    print("people are more than cats")
else:
    print("people are less than cats")  

if cats_number > dogs_number:
    print("cats are more than dogs")
else:
    print("cats are less than dogs")

运行结果如下:
这里写图片描述
第三种结构如下:

#####logic#####
people_number = 20
dogs_number = 10
cats_number = 5

if people_number > dogs_number:
    print("people are more than dogs")     
elif people_number > cats_number:
    print("people are more than cats")     
else:
    print("people are less than cats")  

运行结果如下:
这里写图片描述

解释

if结构是最简单的结构之一。if后面的条件如果为1,即为真,则进入if下面的执行语句,如果为假,则再进行判断或者别的操作。注意一点,缩进问题,执行语句要缩进。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值