Conditional selection
In Python, conditional selection uses
if...else...
statements. Which is determined from the top down, when it is determined that aTrue
time, after completion of execution of the determination program jump condition selection statements.
>>> age = 30
>>> if age > 18: #在条件后需要加冒号
... print 'sdult' #由于采用缩进方式,一定记得要缩进。且缩进方式最好不要混用
... else:
... print 'teenager'
...
sdult
>>>
>>> if age < 6: #使用elif可进行多段的条件判断,注意在有一个条件为真时,将停止向下判断中止选择。
... print 'child'
... elif age < 18:
... print 'teenager'
... elif age < 60:
... print 'adult'
... else:
... print 'older'
...
adult
>>> if age >= 18: #可使用单独的if进行条件选择,当为假时输出结果为None
... print 'adult'
...
adult
>>> if age <= 18:
... print 'teenager'
...
>>> if 3: #if后面的条件判断可以简写,只要其非空,就判断为True。可以是非空整数,字符串,甚至是list
... print 'bingo'
...
bingo
>>> if 0:
... print 'biubiu'
...
>>> if 'abc':
... print 'bingo'
... else:
... print 'biubiu'
...
bingo
>>> if [1,2]:
... print 'biubiu'
...
biubiu
cycle
In Python, there are two ways to express loops:
for ...in...
andwhile
for…in…
for x in L
It is to bring each element in L into the variable x, and then execute the statement of the indented block. L can be list and tuple
>>> g = [98,99,45,34,54]
>>> for x in g:
... print x
...
98
99
45
34
54
>>> sum = 0
>>> for x in g:
... sum = sum + x
...
>>> sum
330
- In the loop, use the range function to calculate the sum of multiple consecutive numbers
>>> for x in range(3):
... sum = sum +1
...
>>> sum
3
>>>
>>> for x in range(3): #range(x)产生一个从0开始到小于x的所有连续整数
... print x
...
0
1
2
while
The while loop will continue to loop as long as the condition is met, and it will automatically exit the loop when the condition is not met.
>>> s = 3
>>> while s > 0:
... print 'this is %d' % s
... s = s-1
...
this is 3
this is 2
this is 1
**Note: raw_input
The return value of using a function to enter the keyboard from the keyboard is a string. When you need to enter a number from the keyboard, you must first convert the content.