python if,for,while

Posted chenhuan001

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python if,for,while相关的知识,希望对你有一定的参考价值。

# -*- coding:utf-8 -*-
# 第四章 if for while

#布尔逻辑

print True == False
print True and False
print True or False
print not True
print True != False

# if elif else
name = lee
if name == chen :
    print yes, you are chen
elif name == le:
    print yes, you are god
elif name == shou:
    print no, get out

# 条件表达式, 类似于?表达式
print Yes if 1 + 1 == 2 else No

# for
# range
print help(range)
print type(range(10))
print range(0, 10, 2)
print range(10, 0, -1)
# range(start, stop=None, step=None) step 是每次递增或者递减(-)的step
for i in range(10, 0, -1) :
    print i

for i in [12,23,lala] :
    print i

# while
name = chen
while True :
    print heheda
    if name == le :
        break
    name = le
    continue
    print "no continue"

结果:

False
False
True
False
True
Yes
Help on built-in function range in module __builtin__:

range(...)
    range(stop) -> list of integers
    range(start, stop[, step]) -> list of integers
    
    Return a list containing an arithmetic progression of integers.
    range(i, j) returns [i, i+1, i+2, ..., j-1]; start (!) defaults to 0.
    When step is given, it specifies the increment (or decrement).
    For example, range(4) returns [0, 1, 2, 3].  The end point is omitted!
    These are exactly the valid indices for a list of 4 elements.

None
<type list>
[0, 2, 4, 6, 8]
[10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
10
9
8
7
6
5
4
3
2
1
12
23
lala
heheda
heheda

 

for or while else

# while or for else
# 循环正常结束(没有break, return),有else的时候会进入else代码段.
for i in range(10) :
    print i
    if i == 3 :
        break
else :
    print "for else"

结果:

0
1
2
3

 

以上是关于python if,for,while的主要内容,如果未能解决你的问题,请参考以下文章

Python学习_4_if_while_for

Python中的if,while,for

python中的if while for语句用法

python学习--流程控制和循环控制(while for if)

python --003--流程控制while,for

python --003--流程控制while,for