day2-python循环判断定义

2017-08-23  本文已影响15人  喵鸢

Part3:循环

while循环

#输出0~10
number = 0
while number < 10:
 print number
 number += 1
 ======= RESTART: C:/Users/Administrator/Desktop/work/python/1.py =======
0
1
2
3
4
5
6
7
8
9

高级主题

小结

a = range(5)
while a:
    print a[-1]
    a = a[:len(a)-1] #将a集合减少一个元素再赋值给a集合,直到a中无元素,循环停止
======= RESTART: C:/Users/Administrator/Desktop/work/python/2.py =======
4
3
2
1
0
>>> 

for循环

基本使用
for item in sequence:
    expressions
+ item:元素
+ sequence:可遍历的集合
example_list = {'dxw',18,'girl',160.0}
for i in example_list:
    print(i)
    print('inner of for')
print('outer of for')
======= RESTART: C:\Users\Administrator\Desktop\work\python\2.py =======
dxw
inner of for
160.0
inner of for
18
inner of for
girl
inner of for
outer of for
进阶
for i in range(0,13,3):
    print(i)
for a in range(5):
    print(a)
======= RESTART: C:\Users\Administrator\Desktop\work\python\2.py =======
0
3
6
9
12
0
1
2
3
高级主题
#列表--最常用,有序,按位移存储
list = ['dxw',18,160.0,'girl','120g']#有中文变成ASCII
infoList = [520,'wxf']
print list
print list[0]
print list[2:4]
print list[3:]
print infoList * 2 #输出两次
print list + infoList #合并

print '-------------------'
#元祖:特殊的列表,不能更新数据,只读的列表
tuple = ('dxw',18,160.0,'girl','120g')
infoTuple = (520,'wxf')
print tuple
print tuple[0]
print tuple[2:4]
print tuple[3:]
print infoTuple * 3
print tuple + infoTuple

print '-------------------'
#字典:键值对,无序,最灵活的内置数据结构
dict = {} #一个空的字典
dict['name'] = 'Wang Xu Feng Frog'
dict['sex'] = 'Frog'
infoDict = {'name':'Dxw','sex':'girl','height':160.0}

print dict['name']
print dict['sex']
print infoDict
print infoDict.keys()
print infoDict.values()
迭代器
# define a Fib class
class Fib(object):
    def __init__(self, max):
        self.max = max
        self.n, self.a, self.b = 0, 0, 1

    def __iter__(self):
        return self

    def __next__(self):
        if self.n < self.max:
            r = self.b
            self.a, self.b = self.b, self.a + self.b
            self.n = self.n + 1
            return r
        raise StopIteration()

# using Fib object斐波那契数列
for i in Fib(5):
    print(i)
def fib(max):
    a, b = 0, 1
    while max:
        r = b
        a, b = b, a+b
        max -= 1
        yield r
# using generator
for i in fib(5):
    print(i)

Part4:判断

if判断

if condition:
    expressions(condition为True则执行)
x=4
y=2
z=3
if x>y:
    print 'x is more than y'
else:
    print 'x is less or equal to y'
print '---------------'

var1,var2= True,False
var = var1 if var1!=var2 else var2
print var 
print '---------------'
if x>1:
    print 'x>1'
elif x<1:
    print 'x<1'
else:
    print 'x=1'
print 'finish'
上一篇下一篇

猜你喜欢

热点阅读