05 python基础四--条件判断及循环

2018-01-19  本文已影响0人  祐吢房_2c9a

1. 条件判断

计算机之所以能做很多自动化的任务,就是因为它可以自己做条件判断。每种语言都离不开条件判断,无非是语法不一致而已。故此处只给出具体实例,不做过多讲解。

# eg1  if ... else ...
>>> age = 3
>>> if age >= 18:
...     print('your age is',age)
...     print('adult')
... else:
...     print('your age is',age)
...     print('teenager')
... 
('your age is', 3)
teenager

# eg2 if ... elif ... else ...
>>> age = 3
>>> if age >= 18:
...     print('adult')
... elif age >= 6:
...     print('teenager')
... else:
...     print('kid')
... 
kid

2. 循环

# 例1
>>> names = ['liheng','wenxiu','yuling']
>>> for name in names:
...     print(name)
... 
liheng
wenxiu
yuling

# 例2
>>> s = 0
>>> for i in (1,2,3,4,5):
...     s = s + i 
... 
>>> print(s)
15
>>> range(5)
[0, 1, 2, 3, 4]
>>> list(range(5))
[0, 1, 2, 3, 4]

>>> sum = 0
>>> for i in list(range(5)):
...     sum = sum + i
... 
>>> print(sum)
10
>>> s = 0 
>>> n = 99
>>> while n > 0:
...     s = s + n
...     n = n - 2
... 
>>> print s
2500
 while n < 100:
...     n = n + 1
...     if n % 2 == 0:
...         continue
...     print(n)
... 
1
3
5
7
9
11
13
15
17
19
21
23
25
27
29
31
33
35
37
39
41
43
45
47
49
51
53
55
57
59
61
63
65
67
69
71
73
75
77
79
81
83
85
87
89
91
93
95
97
99
上一篇下一篇

猜你喜欢

热点阅读