Python之loops

    • for
    • While

一般最常使用的循环语句就是for和while了。

for

#####loops_for#####
number = [1,47,24,9]
pets = ['dogs','cats','birds']
mix = [1,'dogs',3,'cats',6,'birds']

for number in number:
    print(f"this is count {number}")

for pet in pets:
    print(f"I keep a pet like {pet}")

for mix in mix:
    print(f"mix here is {mix}")

newlist = []
for i in range(0,3):
    print(f"adding element{i} to the list")
    newlist.append(i)

for ele in newlist:
    print(f"newlist element is {ele}")

运行结果如下:

this is count 1
this is count 47
this is count 24
this is count 9
I keep a pet like dogs
I keep a pet like cats
I keep a pet like birds
mix here is 1
mix here is dogs
mix here is 3
mix here is cats
mix here is 6
mix here is birds
adding element0 to the list
adding element1 to the list
adding element2 to the list
newlist element is 0
newlist element is 1
newlist element is 2

这个感觉没什么好讲解的,用法在例子中体现得很清楚了。append()函数就是向其中添加元素的函数。

While

#####loops_while#####
i = 0
numbers = []

while i<4:
    print(f"i here is {i}")
    numbers.append(i)

    i = i+1
    print(f"now , numbers is ",numbers)

运行结果如下:
Python之loops_第1张图片
感觉while也没什么好讲的,大部分的编程语言,for和while都是类似的。注意是不要出现死循环什么的就好了,逻辑通了就好了。

你可能感兴趣的:(Python,3)