Python Crash Course读书笔记 - 第5章:IF STATEMENTS

简单示例

$ cat months.py
months = ['jan', 'feb', 'march', 'apr']
for m in months:
        if m == 'apr':
                print(m.upper())
        else:
                print(m.title())
$ python months.py
Jan
Feb
March
APR

几点需要说明:

  1. if 和else句末都有分号(:
  2. 等于用==,而不是=。后者表示赋值。
  3. for循环下的4行都需缩进

条件测试

if是条件测试,返回TrueFalse。注意,这两个值大小写敏感。
测试相等用==,和C语言一样。不等于用!=.

>>> n=1
>>> n==1
True
>>> n=1
>>> n==2
False
>>> n != 2
True

字符串的比较是区分大小写的,可以用lower或upper方法做不区分大小写的比较。
数字的比较还可以用>, <, >=<=

如果要结合多个条件测试,可以用andor
建议为各条件加上(),已避免猜测优先级。

检查某值是否在列表中,innot in

>>> nums=[1,2,3,4]
>>> 2 in nums
True
>>> 5 in nums
False
>>> 5 not in nums
True

条件测试也成为布尔表达式,其返回布尔值,即TrueFalse:

>>> a = True
>>> a
True
>>> a = False
>>> a
False
>>> a = TRUE
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'TRUE' is not defined

if语句

if语句的第一种形式:

if conditional_test:
    do something

第二种形式:

if conditional_test:
    do something
else:
	do something

最复杂的形式, 其中elif可出现多次。elif和else都不是必需的:

if conditional_test:
	do something
elif:
	do something
else:
	do something

if语句与List结合

if后加List可判断List是否为空:

>>> months=[]
>>> if months:
...     print('list is not empty')
...
>>> if not months:
...     print('list is empty')
...
list is empty

if可以与List的for循环结合

>>> nums=[1,2,3,4]
>>> for n in nums:
...     if n == 4:
...             print('My birth month')
...
My birth month

美化if语句

在比较符号前后都需要单个空格。例如a > 4胜过a>4

发布了352 篇原创文章 · 获赞 42 · 访问量 55万+

猜你喜欢

转载自blog.csdn.net/stevensxiao/article/details/103983343