← 返回资讯屏轩教育 · 行业资讯

KS3 Python编程基础 变量 循环 函数 入门 | KS3 Python Basics: Variables, Loops, Functions Intro

2026-09-01 03:07 · 本文部分内容由AI辅助创作

KS3 Python编程基础 变量 循环 函数 入门

Python 是目前全球最流行的编程语言之一,也是英国 KS3 阶段(11至14岁)计算机课程的首选入门语言。它语法简洁、接近英语,用缩进代替花括号,出错信息清楚易懂。对于初学者来说,Python 能让你把注意力集中在"解决问题"本身,而不是纠结复杂的语法细节。学好 KS3 阶段的 Python 基础,你将轻松衔接 GCSE 计算机科学,也为未来的 A-Level 甚至大学学习打下扎实根基。本文围绕变量、输入输出、条件判断、循环和函数五大核心知识点,配合可运行的代码示例,帮你一步步建立编程思维。

Python is one of the most popular programming languages in the world, and it is the standard first language in UK Key Stage 3 computing lessons for pupils aged 11 to 14. Its syntax is clean and close to plain English: indentation replaces curly braces, and error messages are easy to understand. For a beginner, Python lets you focus on solving problems instead of wrestling with complicated syntax. A solid grasp of KS3 Python basics prepares you for GCSE Computer Science, and later for A-Level and beyond. This article covers five core topics, variables, input and output, conditionals, loops and functions, with runnable code examples, so you can build computational thinking step by step.

一、认识Python:为什么从Python开始

在英国国家课程中,KS3 计算课要求学生学会设计、编写和调试程序,Python 正是课堂上最常用的工具。它由荷兰程序员 Guido van Rossum 于1991年发布,设计哲学强调代码可读性。Python 的缩进规则强迫程序员写出整齐的代码,这其实是一种"温柔的训练"。此外,Python 的应用范围极广,从网页开发、数据分析到人工智能,全都在使用它。学 Python 不只是学一门语言,更是学习一种思考方式,这种"计算思维"会伴随你一生。

In the UK National Curriculum, KS3 computing requires pupils to design, write and debug programs, and Python is the tool most classrooms use. It was released in 1991 by Dutch programmer Guido van Rossum, with a design philosophy that puts readability first. Python's indentation rules force you to write tidy code, which is gentle training for good habits. Python is also everywhere: web development, data analysis and artificial intelligence all rely on it. Learning Python is not just learning a language, it is learning a way of thinking, and this computational thinking stays with you for life.

二、第一个程序:print 输出

几乎所有 Python 教程都以 print() 开场,因为它能立刻让你看到程序的输出。字符串必须用引号包起来,单引号双引号都可以。print() 可以同时输出多项内容,用逗号分隔,输出时自动加入空格。试着运行下面的代码,你会看到程序在屏幕上"说话"了。把 print 想象成程序的小喇叭,任何你想确认的值都可以通过它喊出来。学会 print,你就掌握了观察程序运行的第一种工具。

Almost every Python tutorial starts with print(), because it lets you see program output instantly. Strings must be wrapped in quotes, either single or double. print() can output several items at once, separated by commas, with a space added between them automatically. Run the code below and you will see the program "speak" on the screen. Think of print as a loudspeaker: anything you want to check can be shouted out through it. Once you master print, you own the first tool for observing how a program behaves.

print("Hello, World!") print("My name is", "Python") print(3 + 4)

三、注释与代码风格

注释是写给人类看的说明文字,Python 用 # 开头表示注释,程序运行时会被忽略。好的注释能解释"为什么这样做",而不是重复代码本身。同时,变量命名和空行也属于代码风格的一部分。KS3 课程作业和测验中,老师会检查你的代码是否清晰易读。养成写注释、用有意义的变量名的习惯,从第一天开始就很重要。整洁的代码不仅好看,也更容易找错误。

Comments are notes for humans, not the computer. In Python a line starting with # is a comment, and Python ignores it when running. Good comments explain why the code does something, rather than repeating what the code says. Naming and blank lines are also part of code style. In KS3 coursework and tests, teachers check that your code is clear and readable. Build the habit of commenting and using meaningful variable names from day one. Tidy code is not just prettier, it is also much easier to debug.

# This program calculates the area of a rectangle length = 6 width = 4 area = length * width # multiplication print(area)

四、变量与数据类型

变量是存放数据的"带名字的盒子"。在 Python 中用等号赋值,例如 score = 85,不需要像 C 语言那样声明类型。四种基本数据类型要记牢:int 整数、float 浮点数、str 字符串、bool 布尔值(True 或 False)。变量名只能包含字母、数字和下划线,不能以数字开头,也不能与 if、for、while 等关键字重名。Python 是动态类型语言,变量的类型可以改变,但初学阶段建议保持类型稳定,避免混淆。可以用 type() 函数查看一个数据的类型。

A variable is a named box that stores data. In Python you assign a value with the equals sign, for example score = 85, with no type declaration as in C. Memorise the four basic data types: int for whole numbers, float for decimals, str for text, and bool for True or False. Variable names may only contain letters, digits and underscores. They cannot start with a digit, and they cannot be reserved keywords such as if, for or while. Python is dynamically typed, so a variable can change type, but for beginners it is wise to keep types stable to avoid confusion. The type() function tells you the type of any value.

age = 13 height = 1.62 name = "Alice" is_student = True print(name, age, height, is_student) print(type(age))

五、运算符与表达式

Python 支持完整的算术运算:+ 加、- 减、* 乘、/ 除(结果是浮点数)、// 整除、% 取余、** 乘方。注意除法与整除的区别:7 / 2 得到 3.5,而 7 // 2 得到 3,7 % 2 得到 1。运算顺序遵循数学规则,括号可以改变优先级。取余运算符 % 在判断奇偶、处理周期性问题时非常有用,是 KS3 常考知识点。整数除法与取余配合使用,还能解决"分东西剩下多少"这类现实问题。

Python supports the full set of arithmetic operators: + add, - subtract, * multiply, / divide which returns a float, // floor divide, % modulo, and ** power. Note the difference between division and floor division: 7 / 2 gives 3.5, while 7 // 2 gives 3 and 7 % 2 gives 1. The order of operations follows maths rules, and brackets change the priority. The modulo operator is very useful for checking odd and even numbers and for solving pattern problems, a favourite in KS3 tests. Floor division and modulo together even solve real-life questions like "how many boxes and how many items are left over".

print(7 / 2) # 3.5 print(7 // 2) # 3 print(7 % 2) # 1 print(2 ** 10) # 1024 print((3 + 5) * 2) # 16

六、input 输入与类型转换

input() 让程序与用户互动,它会把用户输入的内容作为字符串返回。做算术之前,必须用 int() 或 float() 把输入转换成数值,例如 n = int(input("请输入一个数字:"))。如果忘记转换,把字符串与数字相加会抛出 TypeError。这是初学者最常遇到的问题之一。如果转换本身失败(比如输入了字母),程序会抛出 ValueError,之后可以学习 try except 来优雅处理。记住一句话:input 永远返回字符串。

input() makes a program interactive. It always returns whatever the user types as a string. Before doing arithmetic you must convert the input with int() or float(), for example n = int(input("Enter a number: ")). If you forget, adding a string to a number raises a TypeError, one of the most common beginner issues. If the conversion itself fails, for example the user types letters, Python raises a ValueError, which you can handle gracefully later with try and except. Remember one rule: input always returns a string.

name = input("What is your name? ") age = int(input("How old are you? ")) print("Hello", name, "next year you will be", age + 1)

七、条件判断:if elif else

程序经常需要根据条件做出不同选择。if 后跟条件、冒号,缩进的代码块在条件为真时执行;elif 检查下一个条件;else 处理所有其他情况。比较运算符包括 == 等于、!= 不等于、< 小于、> 大于、<= 小于等于、>= 大于等于。多个条件可以用 and、or、not 组合。特别注意:判断相等用两个等号 ==,单个等号是赋值,混用会导致语法错误或逻辑错误。缩进必须一致,通常用 4 个空格。

Programs often need to make decisions. The if statement tests a condition followed by a colon, and the indented block runs when it is true. elif checks the next condition, and else catches every other case. Comparison operators include == equal, != not equal, < less than, > greater than, <= less than or equal, and >= greater than or equal. Combine conditions with and, or and not. Be careful: equality uses two equals signs, while a single equals sign assigns a value. Mixing them up causes syntax or logic errors. Keep indentation consistent, normally four spaces.

score = int(input("Enter your score: ")) if score >= 85: print("Excellent") elif score >= 60: print("Pass") else: print("Keep trying")

八、循环:for 与 while

循环让一段代码重复执行,是编程的核心能力。for 循环适合"知道次数"的情况,常与 range() 搭配,例如 for i in range(5) 执行 5 次,range(1, 6) 则产生 1 到 5。while 循环在条件为真时反复执行,适合"不确定次数"的情况,但要确保条件最终变为假,否则就是无限循环。break 可以提前跳出循环,continue 跳过本次循环的剩余部分。循环嵌套(循环里套循环)可以处理二维问题,比如画棋盘格。

Loops run a block of code repeatedly, a core programming skill. A for loop suits a known number of repeats and works with range(), for example for i in range(5) runs five times, and range(1, 6) produces 1 to 5. A while loop repeats while a condition is true, which fits unknown-length repetitions, but the condition must eventually become false or you get an infinite loop. Use break to exit early and continue to skip the rest of the current pass. Nested loops, a loop inside a loop, handle two-dimensional problems such as drawing a checkerboard.

for i in range(1, 6): print(i, "squared is", i * i) total = 0 while total < 100: total = total + 25 print("Total:", total)

九、函数:def

函数把一段完成特定任务、可重复使用的代码打包起来,避免复制粘贴。用 def 定义:def 函数名(参数):,函数体缩进,用 return 返回结果。函数可以接收参数,也可以没有参数;可以有返回值,也可以只执行操作。把复杂程序拆成小函数,每个函数只做一件事,代码会变得清晰易读、方便测试。这是模块化编程的思想,也是 KS3 的高阶内容。函数名也要用有意义的词,例如 calculate_average 而不是 ca。

A function packages reusable code that performs one task, avoiding copy and paste. Define it with def: def function_name(parameters):, with the body indented, and use return to send back a result. Functions may take parameters or not, and may return values or simply perform actions. Splitting a complex program into small functions, each doing one thing, makes code clear, readable and easy to test. This is modular programming, and a higher-level KS3 topic. Choose meaningful function names too, such as calculate_average rather than ca.

def greet(name): return "Hello " + name def double(x): return x * 2 print(greet("Sam")) print(double(21))

十、综合实战:猜数字小项目

把前面所有知识串起来,最好的方式是做一个小项目。猜数字游戏是经典练习:程序随机生成一个 1 到 20 的整数,用户循环输入猜测,程序提示"太大"或"太小",直到猜中为止。这个小项目同时用到 input、int 转换、while 循环、if 条件判断和随机数模块 random。完成后试着加一个次数统计功能,看看谁用最少的次数猜中。动手做项目,比单纯背语法有效十倍。

The best way to link everything together is a small project. The number guessing game is a classic: the program picks a random integer from 1 to 20, the user keeps guessing, and the program says "too high" or "too low" until the guess is correct. This tiny game uses input, int conversion, a while loop, if conditions and the random module. After it works, add a counter to show how many guesses were needed. Building projects teaches you ten times more than memorising syntax.

import random secret = random.randint(1, 20) guess = 0 while guess != secret: guess = int(input("Guess a number: ")) if guess > secret: print("Too high") elif guess < secret: print("Too low") print("Correct!")

十一、常见错误与调试

学会读错误信息,是编程进步最快的方式。SyntaxError 语法错误,通常是漏了冒号、括号或引号;NameError 名字未定义,多半是拼写错误或变量未赋值;TypeError 类型错误,比如字符串与数字相加;IndexError 索引越界,常发生在列表操作中;IndentationError 缩进错误。阅读报错时先看最后一行,它指出真正出错的位置。最实用的调试方法,是在关键位置用 print() 输出中间变量,观察程序执行到哪里、数值是什么。

Learning to read error messages is the fastest way to improve. SyntaxError usually means a missing colon, bracket or quote. NameError means a name is not defined, often a spelling mistake or an unassigned variable. TypeError happens when types clash, such as adding a string to a number. IndexError means you accessed an index that does not exist, common with lists. IndentationError means your indentation is wrong. When reading a traceback, start from the last line, which points at the real problem. The most practical debugging technique is printing intermediate variables with print() to see where the program goes and what the values are.

十二、学习建议与下一步

编程是练出来的,不是看出来的。每学一个知识点,就在编辑器中亲手敲一遍、运行一遍,再试着改动参数观察结果。把大问题拆成小步骤,先写伪代码再写真代码。注释记录你的思路,方便回看。每天坚持 20 分钟,效果远好于周末突击两小时。下一步可以学习列表 list、字典 dict、turtle 画图和简单小游戏项目。遇到问题先自己调试 10 分钟,再求助老师或同学,你的独立解决问题的能力会飞速提升。

Programming is learned by doing, not by watching. After each concept, type it yourself and run it, then change values and observe the results. Break big problems into small steps, write pseudocode first and then real code. Use comments to record your thinking for later review. Twenty minutes every day beats a two-hour cram at the weekend. Next steps include lists, dictionaries, turtle graphics and small game projects. When stuck, debug on your own for ten minutes before asking for help, and your independent problem-solving skills will grow quickly.

牛津国际课程教材小学计算机教师指南4-6级(第二版)¥329.0📱 去京东购买京东精选

广告 / Sponsored
备考2027年高级经济师教材书人力资源工商管理金融财税建筑与房地产财政税收知识产权农业保险实务运输旅游2026考试历年…
经济 备考教辅 · 正版现货 · 学习备考通用
查看详情 / View on Taobao参考价 ¥33.15
广告 / Sponsored
Pearson Edexcel International AS/A Level 培生爱德思 Alevel 考试 Ph…
物理 备考教辅 · 正版现货 · 学习备考通用
查看详情 / View on Taobao参考价 ¥305.0
更多咨询请联系16621398022(同微信)

A-Level / GCSE / IB / KS2-KS3 全科辅导

Visit aleveler.com
备考资讯每日更新,关注不错过
考纲变化 · 科目分析 · 学习方法
扫码关注公众号 tutorhao
在微信里长按二维码识别关注
或截图后用「扫一扫 → 相册」选择本图
公众号:tutorhao