python笔记5-循环for和while

    技术2022-07-11  83

    1.for

    获取列表中的项:

    for name in ['Christopher','Susan']: print(name) ''' name为变量,in后面的是循环列表,for会自动遍历列表 输出结果: Christopher Susan '''

    指定循环次数:

    for index in range(0,2): print(index) ''' range为内置函数,会自动创建一个整数列表 这里的0是开始位置,2是停止位置,左闭右开区间 即创造的数组为[0,1] 输出结果: 0 1 '''

    2.while

    while可以指定循环的具体条件,条件为真就执行。

    在下面这个例子中一定要记得写条件变化(change the condition,比如index),不然会一直死循环

    names = ['Christopher','Susan'] index=0 while index <len(names): print(names[index]) index = index+1

    通常使用while,条件都会自动变化,如按行读取列表或文件

     

     

    使用for

    people = {'Christopher','Susan'} for name in people: print(name)

    输出

    Christopher Susan

    使用while

    people = ['Christopher','Susan'] # for name in people: # print(name) index=0 while index <len(people): print(people[index]) index +=1

    可得到相同输出

    Processed: 0.011, SQL: 9