对于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下面的执行语句,如果为假,则再进行判断或者别的操作。注意一点,缩进问题,执行语句要缩进。