KS3 Python 变量 类型转换 循环 函数 列表
KS3 的计算机课从图形化编程转到文本编程时,Python 几乎是默认选择,语法干净、报错直白,能把注意力留在逻辑上。这篇文章把第三学段最常见的十一个知识点串起来,从第一条 print 一直讲到函数和报错信息,每个知识点都配了容易踩的坑。文中提到的课程要求来自英国教育部(Department for Education)2013 年发布、2014 年 9 月首次施教的国家课程 Computing programmes of study。读的时候建议打开一个解释器,边看边敲,光看代码很难记住缩进和括号的细节。
When computing moves from blocks to text at key stage 3, Python is usually the language schools pick, largely because its syntax stays out of the way of the logic. The eleven topics below run from the first print statement to functions and error messages, and each one names the mistake that pupils actually make. The curriculum expectations quoted here come from the 2013 national curriculum computing programmes of study, first taught in September 2014. Keep an interpreter open while reading, since indentation and brackets are learned by typing rather than by looking.
一、print 函数与注释:第一条能跑的程序
在 KS3 阶段,Python 通常被选作第一门文本语言,2013 年的国家课程文件要求学生在第三学段使用两门以上编程语言,其中至少一门必须是文本语言。Python 的语法接近英文,写的时候少很多括号和分号,适合把注意力放在逻辑上。第一个程序一般是 print("Hello"),print 是 Python 3 的内置函数,括号必须成对,双引号中间的内容叫字符串。单行注释用井号开头,解释器会直接跳过,多行注释习惯用三个双引号包起来。很多学生以为注释是写给机器看的,其实注释只服务于读代码的人,机器一个字都不执行。常见的错误是把 print 写成 Print,Python 区分大小写,函数名错了会直接报 NameError。文件名建议用英文小写加下划线,避免空格和中文,某些教学环境里中文文件名会让解释器找不到模块。写完存成 .py 文件,在命令行里输入 python 加文件名就能运行。
Most schools in England teach Python as the first text-based language, because the 2013 national curriculum asks for two languages at key stage 3 with at least one of them textual. The gap between a pupil who can copy a program and one who can predict what it will do shows up almost immediately in year 7. Anyone who types a capital P in print meets their first NameError within the first lesson, which is a useful introduction to case sensitivity. Running the saved file from the command line, rather than only from an editor button, also shows what an interpreter does with the text on disk.
二、变量名与赋值语句:值存在哪里
变量在 Python 里更像贴在值上的名字,而不是一只装东西的盒子。执行 age = 12 的时候,Python 先在内存里生成整数 12,再让 age 指向它。后面写 age = age + 1,会生成新的整数 13 并让 age 改指向新值,原来的 12 并没有被改掉。变量名只能由字母、数字和下划线组成,不能以数字开头,也不能用 if、for、class 这类保留字。命名习惯上通常用小写字母加下划线,score_total 比 ScoreTotal 更符合 Python 社区规范,后者虽然合法,却容易被误认为类名。学生最常把变量名写错一个字母,然后又用旧名字去 print,结果是 NameError 说这个名字没有定义。赋值号等号不是数学里的相等,a = b 表示把 b 的值交给 a,判断相等要用两个等号。
Treating a variable as a label rather than a container clears up most of the confusion around reassignment. When a pupil writes total = total + 5, the interpreter builds a new integer and moves the label, so any earlier reference keeps its old value. Naming rules matter in practice, since Python allows mixed case but the community convention of lower-case words joined by underscores prevents a variable from being mistaken for a class. A single mistyped letter is behind a large share of the NameError messages seen in year 8 classrooms, and reading the error line carefully usually settles it in seconds.
三、三种数据类型与 input 的字符串陷阱
KS3 的程序里出现最多的类型是整数 int、小数 float 和字符串 str,另外还有只取 True 与 False 的布尔 bool。用 type() 可以查出当前值属于哪一种,这个习惯比背概念有用得多。input() 是一个容易踩坑的地方,不管用户敲进去的是什么,它拿回来的永远是字符串。所以 input() 之后直接做加法,会把两个数字拼成一段文字,敲 3 和 4 得到 34 而不是 7。要算数就得先转换,写成 int(input()) 或 float(input()),输入非数字时 int() 会抛出 ValueError。很多学生以为屏幕上显示 3 就是数字 3,其实显示与类型无关,print 什么都能显示。习惯上把从 input 拿到的值命名成 age_text 而不是 age,写完自己一眼就能看出这里还需要转换。
The most frequent bug in key stage 3 Python work is arithmetic performed on text. Whatever the user types, input() hands back a string, so adding two responses joins them rather than summing them. Wrapping the call in int() or float() fixes the type, although a non-numeric reply then raises ValueError and needs a check before the calculation runs. Checking a value with type() during debugging is quicker than guessing, and naming a raw response age_text is a small habit that stops the same mistake being repeated next lesson.
四、字符串拼接与 f-string 的写法
字符串可以用加号拼接,也可以在 print 里用逗号分开输出,两者的区别在于逗号会自动插一个空格。想把变量嵌进一句话里,Python 3.6 之后最常用的写法是 f-string,在引号前加一个 f,把变量名放进花括号。name 存的是 Ada 的时候,f"Hello {name}" 得到 Hello Ada,读起来接近自然语言。加号拼接遇到数字会报错,字符串加 90 会抛 TypeError,因为字符串只能和字符串相加。这时要么先 str(90) 转换,要么干脆改用 f-string,后者在 KS3 的作业里更省事。字符串的长度用 len() 取,索引从 0 开始,s[0] 是第一个字符,s[-1] 是最后一个。常见的错误是把花括号写成圆括号,f-string 里只有花括号才会被替换。
Joining text is where beginners first meet a TypeError, because the plus sign refuses to mix a string with an integer. The f-string syntax added in Python 3.6 sidesteps the problem, since a single f before the opening quote turns anything inside curly brackets into its printed form. Comparing the two styles early pays off, because concatenation forces explicit str() calls while f-strings keep the sentence readable and the conversion automatic. Character positions start at zero, so a pupil who wants the first letter should reach for s[0] rather than s[1].
五、整除、取余与运算优先级
Python 的加、减、乘直接对应加号、减号和星号,除法斜杠的结果一定是小数,就算 10 除以 2 也得到 5.0。要整数结果得用两个斜杠做整除,10 // 3 得 3;取余用百分号,10 % 3 得 1,余数在判断奇偶和分组合计时特别方便。幂运算用两个星号,2 ** 10 等于 1024。运算顺序与数学一致,括号先算,然后乘除与取余,最后加减,混在一起时加括号最省心。负数除法有个容易忽略的细节,-10 // 3 得 -4 而不是 -3,因为整除向下取整而不是向零取整。常见的错误是整除与除法弄混,写成分数题之后结果多出一位小数。判断能否整除,用 n % 2 == 0 比用除法再比较更可靠,浮点数参与时更明显。
Division in Python always produces a float, even when the two numbers divide exactly, so ten divided by two gives 5.0 and not 5. Floor division drops the decimal part downwards, which is why -10 // 3 lands on -4 rather than -3, while the modulo operator returns what is left over. Testing whether a number is even is safer with n % 2 == 0 than with a division followed by a comparison, especially once floats enter the calculation. Order of operations follows maths, and adding brackets costs nothing while removing most of the ambiguity.
六、布尔表达式与 if 分支的缩进规则
判断语句的骨架是 if 加条件加冒号,下面缩进的内容属于这个分支,缩进在 Python 里是语法的一部分,不是排版。比较运算包括两个等号的等于、感叹号加等号的不等于、大于、小于以及大于等于、小于等于,注意两个等号才是比较。多个条件可以用 and、or、not 组合,and 要求两边都成立,or 只要一边成立。elif 可以有多个,else 放最后,从上往下判断,命中第一个成立的分支就跳出整条链。很多学生以为缩进用几个空格无所谓,混用空格和制表符会直接得到 IndentationError。写条件时把最可能成立的分支放在前面,程序少做没必要的判断。
Indentation is not decoration in Python, since it is the syntax that marks which lines belong to a branch. A comparison needs two equals signs, while a single equals sign assigns, and mixing the two produces a SyntaxError rather than a wrong answer. Conditions can be combined with and, or and not, and the interpreter stops at the first branch that evaluates to True. Mixing tabs and spaces is the usual cause of an IndentationError in school files, so setting the editor to insert four spaces avoids a whole family of confusing messages.
七、for 循环与 range 的边界
for 循环用来重复固定次数,或者遍历一串已有的数据。range(5) 给出 0 到 4 这五个数,终点不包含在内,这一点和很多人的直觉相反。range(1, 6) 得到 1 到 5,range(0, 10, 2) 得到 0、2、4、6、8,第三个参数是步长。循环变量在每一轮会重新赋值,循环体靠缩进界定,缩进结束循环也就结束。累加是最常见的练习,先写 total = 0,再在循环里写 total = total + i,最后打印出来。常见的错误是把 print 放在循环外面却以为每轮都会打印,或者放在里面导致打印一堆中间值。遍历字符串也行,for ch in "abc" 会依次拿到三个字符。
A for loop over range runs a fixed number of times, and the stop value is excluded, which surprises nearly everyone at first. range(1, 6) therefore produces 1 to 5, while a third argument sets the step so that range(0, 10, 2) gives the even numbers below ten. Accumulating a total needs the variable created before the loop, otherwise each pass restarts the sum from zero. Where print sits relative to the indentation decides whether the program shows one result or a long column of intermediate values.
八、while 循环与退出条件
while 循环只要条件为真就一直执行,适合事先不知道要循环多少次的场景,比如让用户反复输入直到猜对。写 while 之前先想清楚哪个变量会让条件变假,漏掉这一步就是死循环,屏幕上刷满输出,只能按 Ctrl 加 C 停下。计数器要在循环体里自增,count = count + 1 这一句常被忘掉。break 可以立刻跳出循环,continue 跳过本轮剩下的代码直接进入下一轮,这两个关键字在 KS3 的练习里不算必需,但读别人的代码时会遇到。学生最容易在 while 里用了比较运算符却忘了更新变量,条件永远成立。用 while 处理输入时,记得先给变量一个初始值,否则第一轮判断就会报 NameError。
A while loop suits problems where the number of repetitions is unknown in advance, such as asking for input until the answer is right. Before writing one, pupils should identify the variable that will eventually make the condition false, since without it the program loops for ever and has to be stopped with Ctrl and C. The counter must be updated inside the block, and forgetting that single line is the most common reason a while loop never ends. break and continue are worth recognising when reading someone else's code, even if most key stage 3 exercises never need them.
九、列表的索引、切片与 append
列表用方括号写,元素之间用逗号隔开,scores = [72, 85, 61] 就是一个包含三个整数的列表。索引从 0 开始,scores[0] 是 72,scores[-1] 是最后一个,切片 scores[0:2] 取前两个元素,终点同样不包含。append() 在末尾加一个元素,len() 返回长度,sum() 可以直接求和,max() 与 min() 取最大最小。遍历列表可以写 for s in scores,需要下标时用 for i in range(len(scores)),这时 scores[i] 才是当前元素。常见的错误是把 append 当成返回值使用,写 scores = scores.append(90) 会让 scores 变成 None,正确写法是单独一行 scores.append(90)。列表里的元素类型可以不同,但做数学运算前最好保证全是数字。
Lists are written with square brackets and hold items in order, so scores[0] is the first score and scores[-1] the last. Slicing with scores[0:2] stops before the second index, mirroring the rule already met in range. append changes the list in place and returns None, which is why scores = scores.append(90) quietly destroys the list; the call belongs on its own line. Summing and counting are handled by sum() and len(), and a plain for loop over the list is usually clearer than indexing by hand.
十、def 定义函数与 return 的作用
函数把一段重复使用的代码包起来,用 def 定义,括号里放参数,冒号后面缩进写函数体。定义函数只是告诉 Python 有这么一段代码,真正执行要等调用,写 area(3, 4) 时才运行。return 把结果交回调用处,没有 return 的函数返回 None,这也是 print 与 return 混淆的根源。print 只是把值显示出来,return 才让结果能被继续计算,函数里打印完却忘了 return,外面的变量拿到的就是 None。局部变量只在函数内部存在,函数执行完就消失,这是作用域最基本的规则,也是学生问得最多的一处。参数名和外面的变量名可以相同,两不相干。
A function exists to name a piece of work that will be used more than once, and def only defines it until a call actually runs the body. The difference between print and return decides whether the result can be reused: printing shows a value on screen, while return hands it back to the line that made the call. A function that prints but returns nothing gives back None, which is why a later calculation on its output fails with a TypeError. Variables created inside the body disappear once the call ends, and that isolation is a feature rather than an obstacle.
十一、四类报错信息与逐行调试
报错信息不要只看最后一行,Python 的 traceback 会指出文件名和出错的行号,从下往上读通常最快。SyntaxError 多半来自少一个冒号、括号不配对或者引号没闭合,解释器在运行之前就会拦下。NameError 说明这个名字从没被赋值,常见于拼错变量名,或者变量在函数外部使用。TypeError 是类型不匹配,把字符串当数字加是最典型的例子。缩进错误会报 IndentationError,空格与制表符混用是最常见的原因。调试时在可疑的位置加一句 print,把中间值打出来,比盯着代码猜要快得多。把大问题拆成能在十行内跑通的小段,先确认输入输出,再拼回去。
Reading the traceback from the bottom is usually fastest, because the last lines give the file name and the line number of the statement that failed. A SyntaxError is caught before anything runs and almost always traces to a missing colon, an unclosed bracket or a quote left open. NameError means the name was never assigned, TypeError means the types do not fit together, and IndentationError points at whitespace that Python cannot interpret. Printing a suspect value part way through the program remains the quickest debugging tool available, and splitting a long script into short blocks that each run correctly saves more time than guessing.
戴睿(dere)Neo优选系列 创意双触摸屏高性能笔记本电脑大学生AI学习商务办公设计炒股娱乐手提轻薄本32/1TB¥4586.0📱 去京东购买京东精选
需要一对一辅导?Need One-on-One Tutoring?
KS3 / GCSE / A-Level / IB 计算机与数学全科辅导
16621398022 同微信
Visit aleveler.com
或截图后用「扫一扫 → 相册」选择本图

