# 1.条件和循环

1.1 if语句

if语句由三部分组成：关键字本身、用于判断结果真假的条件表达式、以及判断为真或非零时执行的代码块，语法如下：

if expression:

expr_true_suite

1.2 多重条件表达式

expr_true_suite

1.3 单一语句的代码块

if expression: expr_true_suite

1.4 else语句

if语句可以和else语句配合使用，如果判断为假，则调用else语句。语法如下：

if expression:

expr_true_suite

else:

expr_false_suite

``` 1 #!/usr/bin/env python
2
3 def showMaxFactor(num):
4     count = num/2
5     while count > 1:
6         if num % count == 0:
7             print ‘largest factor of %d is %d‘ % (num, count)
8             break
9         count -= 1
10     else:
11         print num, ‘is prime‘
12
13 if __name__ == ‘__main__‘:
14     for eachNum in range(10, 21):
15         showMaxFactor(eachNum)
16
17 [[email protected] python]# python maxFact.py
18 largest factor of 10 is 5
19 11 is prime
20 largest factor of 12 is 6
21 13 is prime
22 largest factor of 14 is 7
23 largest factor of 15 is 5
24 largest factor of 16 is 8
25 17 is prime
26 largest factor of 18 is 9
27 19 is prime
28 largest factor of 20 is 10```

## 1.5 elif（即else-if语句）

elif语句用于检查多个表达式是否为真，并在为真时执行代码块中的代码。语法如下：

if expression1:

expr1_true_suite

elif expression2:

expr2_true_suite

elif expression:

exprN_true_suite

else:

none_of_the_above_suite

## 1.6 条件表达式（即"三元操作符"）

>>> x, y = 4, 3

>>> smaller = x if x < y else y

>>> smaller

3

python条件与循环-条件

(0)
(0)