《笨办法学Python》 第32课手记

时间:2022-04-26
本文章向大家介绍《笨办法学Python》 第32课手记,主要内容包括《笨办法学Python》 第32课手记、本节课涉及的知识、基本概念、基础应用、原理机制和需要注意的事项等,并结合实例形式分析了其使用技巧,希望通过本文能帮助到大家理解应用这部分内容。

《笨办法学Python》 第32课手记

本节课讲for循环和list,list里类似于c中的数组,但有区别很大。C语言中的数组是数据类型相同的值的集合,list可以数值和字符及其他数据类型混合。

原代码如下:

the_count = [1, 2, 3, 4, 5]
fruits = ['apples', 'oranges', 'pears', 'apricots']
change = [1, 'pennise', 2, 'dimes', 3, 'quarters']

# this first kind of for-loop goes through a list
for number in the_count:
   print "This is the_count %d" % number

# same as above
for fruit in fruits:
   print "A fruit of type: %s" % fruit

# also we can go through mixed lists too
# notice we have to use %r since we don't know what's in it
for i in change:
   print "I got %r" %i

# we can also build lists, first start with an empty one
elements = []

# then use the range function to do 0 to 5 counts
for i in range(0, 6):
   print "Adding %d to the list." % i
   # append is a function that lists understand
   elements.append(i)

# now we can print them out too
for i in elements:
   print "Element was: %d" % i

结果如下:

i in range(0, 6)表示 i大于0小于6,该语句是循环控制语句,表示执行for循环的条件,满足就执行下面的语句,不满足该条件即跳出循环结束操作。

change = [1, ‘pennise’, 2, ‘dimes’, 3, ‘quarters’],list可以数值和字符混合赋值,但输出是只能是一种格式。 print “I got %r” %i 该课中作者是以字符型数据输出的。

至于函数append

即在列表变量末尾加上一个元素。

我发现一个快捷的打开函数解释文档的方法,那就是在notepad++上打出这个函数,解释文档会自己显示。

本节课涉及的知识

for循环:

for judgement:
   sentence1
   sentence2
   ...

执行步骤如下: judement是一个循环控制语句,由它判定要不要继续执行循环语句。

先执行判断语句,如果不满足条件,跳出循环执行for语句后面的代码;如果满足条件,执行语句1语句2等等,执行后若依然满足条件,则再次执行语句1语句2等等,直到不满足判断语句里的条件为止。judgement里的判断语句通常包含一个变量,每次循环都会修改该变量的值,使得循环执行到期望的时候因条件不再满足跳出循环语句。

常见问题解答,请先记住里面的内容,遇到之后再详解。