Variables, Data Types and Operators in Python | Python 中的变量、数据类型与运算符

📚 Variables, Data Types and Operators in Python | Python 中的变量、数据类型与运算符

In any programming language, variables act as named containers that store values used and manipulated during execution. Understanding how to declare variables, assign values to them, and combine them using operators forms the backbone of writing effective code. This article covers the foundational concepts required for the Edexcel A-Level Computer Science specification, using Python as the teaching language. We will explore primitive data types, type casting, arithmetic, relational, and logical operators, operator precedence, and common pitfalls.

在任何编程语言中,变量都是用来存储和执行期间操纵值的命名容器。理解如何声明变量、赋值以及使用运算符将它们组合起来是编写高效代码的基础。本文涵盖了爱德思 A-Level 计算机科学大纲所需的基础概念,并使用 Python 作为教学语言。我们将探讨基本数据类型、类型转换、算术运算符、关系运算符和逻辑运算符、运算符优先级以及常见陷阱。


1. Variables and Assignment | 变量与赋值

A variable in Python is created the moment you assign a value to it using the assignment operator `=`. No explicit declaration of the data type is required, as Python is dynamically typed. For example, age = 17 creates an integer variable, while name = ‘Alice’ creates a string variable. The identifier on the left side references the object stored in memory.

Python 中,当你使用赋值运算符 `=` 给一个名字赋值时,变量就被创建了。由于 Python 是动态类型语言,不需要显式声明数据类型。例如,age = 17 创建了一个整型变量,而 name = ‘Alice’ 创建了一个字符串变量。左侧的标识符指向内存中存储的对象。

Variable names must adhere to specific rules: they can contain letters, digits, and underscores, but cannot start with a digit. They are case-sensitive (so Score and score are different variables). Python keywords such as if, for, or while cannot be used as variable names.

变量名必须遵循特定规则:它们可以包含字母、数字和下划线,但不能以数字开头。变量名是区分大小写的(因此 Scorescore 是不同的变量)。Python 关键字,如 ifforwhile 不能用作变量名。


2. Primitive Data Types | 基本数据类型

Python provides several built-in data types that represent the kind of value a variable can hold. The most common ones for A-Level are:

Python 提供了多种内建数据类型来表示变量可以持有的值的种类。A-Level 课程中最常见的包括:

  • int – integers, e.g., 42, -7
  • int – 整数,例如 42-7
  • float – decimal numbers, e.g., 3.14, -0.001
  • float – 浮点数,例如 3.14-0.001
  • str – strings, a sequence of characters enclosed in single or double quotes, e.g., ‘Hello’, “world”
  • str – 字符串,用单引号或双引号括起来的字符序列,例如 ‘Hello’“world”
  • bool – Boolean values True or False
  • bool – 布尔值 TrueFalse

You can check the type of a variable using the type() function, which is useful during debugging. For example, type(3.0) returns .

你可以使用 type() 函数检查变量的类型,这在调试时非常有用。例如,type(3.0) 返回


3. Type Casting and Conversion | 类型转换

Sometimes you need to convert a value from one data type to another. This is achieved using constructor functions: int(), float(), str(), and bool(). Implicit conversion also occurs in mixed-type expressions; for example, adding an integer and a float results in a float.

有时你需要将值从一种数据类型转换为另一种。这可以通过构造函数 int()float()str()bool() 实现。在混合类型的表达式中也会发生隐式转换;例如,整数与浮点数相加会产生浮点数。

Explicit conversion is essential when reading input, as input() always returns a string. To perform arithmetic, you must cast the string to a numeric type: num = int(input(‘Enter a number: ‘)). However, attempting to convert a non-numeric string like ‘hello’ to int raises a ValueError.

在读取输入时,显式转换至关重要,因为 input() 总是返回字符串。要执行算术运算,必须将字符串转换为数值类型:num = int(input(‘输入一个数字: ‘))。然而,尝试将像 ‘hello’ 这样的非数字字符串转换为 int 会引发 ValueError


4. Arithmetic Operators | 算术运算符

Arithmetic operators perform mathematical calculations. The standard operators are:

算术运算符执行数学计算。标准运算符包括:

Operator Meaning Example
+ Addition 5 + 2 → 7
Subtraction 5 – 2 → 3
* Multiplication 5 * 2 → 10
/ Division (always returns float) 5 / 2 → 2.5
// Integer division (floor) 5 // 2 → 2
% Modulus (remainder) 5 % 2 → 1
** Exponentiation 5 ** 2 → 25

Note that division / yields a float, while integer division // floors the result toward negative infinity. The modulus operator % is frequently used to test divisibility or cycle through a range.

请注意,除法 / 产生浮点数,而整数除法 // 将结果向负无穷方向取整。取模运算符 % 经常用于测试整除性或循环遍历某个范围。


5. Relational Operators | 关系运算符

Relational operators compare two values and return a Boolean (True or False). They are vital in conditional statements and loops. The operators are:

关系运算符比较两个值并返回布尔值(TrueFalse)。它们在条件语句和循环中至关重要。这些运算符包括:

  • == (equal to)
  • == (等于)
  • != (not equal to)
  • != (不等于)
  • > (greater than)
  • > (大于)
  • < (less than)
  • < (小于)
  • >= (greater than or equal to)
  • >= (大于或等于)
  • <= (less than or equal to)
  • <= (小于或等于)

Be careful not to confuse the assignment operator = with the equality operator ==. Using = in a condition will cause a syntax error.

注意不要将赋值运算符 = 与相等运算符 == 混淆。在条件中使用 = 将导致语法错误。


6. Logical Operators | 逻辑运算符

Logical operators combine Boolean expressions and return a Boolean result. Python uses and, or, and not. These follow the standard truth tables:

逻辑运算符组合布尔表达式并返回布尔结果。Python 使用 andornot。它们遵循标准真值表:

  • A and B is True only if both A and B are True.
  • A and B 仅在 A 和 B 均为 True 时为 True
  • A or B is True if at least one is True.
  • A or B 如果至少有一个为 True,则结果为 True
  • not A inverts the Boolean value.
  • not A 反转布尔值。

Short-circuit evaluation is applied: in A and B, if A is False, B is not evaluated; in A or B, if A is True, B is skipped. This can be used to avoid errors, such as checking that a divisor is not zero before division.

这里应用了短路求值:在 A and B 中,如果 A 为 False,则不会计算 B;在 A or B 中,如果 A 为 True,则跳过 B。这可以用来避免错误,比如在除法之前检查除数不为零。


7. Operator Precedence | 运算符优先级

When an expression contains multiple operators, evaluation is governed by precedence rules. From highest to lowest precedence in Python:

当表达式包含多个运算符时,求值顺序由优先级规则决定。Python 中从高到低的优先级如下:

Precedence Operators
Highest **
+x, -x (unary)
*, /, //, %
+, – (binary)
==, !=, >, <, >=, <=
not
and
Lowest or

Parentheses () can override the default precedence to make the intended order of evaluation explicit. For example, (5 + 3) * 2 yields 16, while 5 + 3 * 2 yields 11 because multiplication is evaluated before addition.

括号 () 可以覆盖默认优先级,使求值顺序明确。例如,(5 + 3) * 2 得到 16,而 5 + 3 * 2 得到 11,因为乘法优先于加法。


8. String Operations and Concatenation | 字符串操作与连接

Strings can be manipulated using operators. The + operator concatenates (joins) strings, while the * operator repeats a string multiple times. For example, ‘Hello’ + ‘ ‘ + ‘World’ produces ‘Hello World’, and ‘Ha’ * 3 gives ‘HaHaHa’.

字符串可以使用运算符进行操纵。+ 运算符用于连接(拼接)字符串,而 * 运算符用于重复字符串多次。例如,‘Hello’ + ‘ ‘ + ‘World’ 生成 ‘Hello World’‘Ha’ * 3 得到 ‘HaHaHa’

It is important to remember that concatenation requires both operands to be strings. Attempting ‘Score: ‘ + 95 will cause a TypeError; you must convert the number to a string: ‘Score: ‘ + str(95).

必须记住,连接操作要求两个操作数都是字符串。尝试 ‘Score: ‘ + 95 会导致 TypeError;你必须将数字转换为字符串:‘Score: ‘ + str(95)


9. Compound Assignment Operators | 复合赋值运算符

Compound operators combine an arithmetic operation with assignment, making code more concise. Examples include +=, -=, *=, /=, //=, %=, and **=. For instance, x += 5 is equivalent to x = x + 5. These operators are particularly useful in loops and accumulators.

复合运算符将算术运算与赋值组合在一起,使代码更加简洁。示例包括 +=-=*=/=//=%=**=。例如,x += 5 等同于 x = x + 5。这些运算符在循环和累加器中特别有用。


10. Expressions in Conditions and Boolean Logic | 条件与布尔逻辑中的表达式

Combining relational and logical operators allows the creation of complex conditions. For example, to test whether a number is within a range, you can write if 10 <= x <= 20:, which is a chained comparison unique to Python and is equivalent to if x >= 10 and x <= 20:.

组合关系运算符和逻辑运算符可以创建复杂的条件。例如,要测试一个数字是否在某个范围内,可以写 if 10 <= x <= 20:,这是 Python 中特有的链式比较,等同于 if x >= 10 and x <= 20:

Be mindful of De Morgan’s laws when negating conditions. For instance, not (A or B) is equivalent to not A and not B. Using these laws can simplify logical expressions and improve readability.

在否定条件时要注意德摩根定律。例如,not (A or B) 等同于 not A and not B。运用这些定律可以简化逻辑表达式并提高可读性。


11. Common Pitfalls and Best Practices | 常见陷阱与最佳实践

A common mistake is using a variable before it has been assigned a value, which raises a NameError. Always initialise variables. Also, be aware of integer division surprises: in Python, -7 // 2 yields -4 (floor), not -3, because it rounds toward negative infinity.

一个常见错误是在变量赋值之前使用它,这会引发 NameError。始终要初始化变量。另外,要注意整数除法的意外:在 Python 中,-7 // 2 得到 -4(向下取整),而不是 -3,因为它向负无穷方向舍入。

Choosing descriptive variable names improves code clarity. Follow the PEP 8 style guide: use lowercase with underscores for variable names (snake_case). Avoid using ambiguous names like data or value without context.

选择描述性的变量名可以提高代码清晰度。遵循 PEP 8 风格指南:变量名使用小写字母加下划线(蛇形命名法)。避免在没有上下文的情况下使用像 datavalue 这样的模糊名称。


12. Practical Example: Temperature Conversion | 实际示例:温度转换

Let’s apply these concepts in a simple program that converts Celsius to Fahrenheit. The formula is: F = (C × 9/5) + 32. The code reads input, converts it to a float, performs the calculation, and prints the result.

让我们在一个将摄氏温度转换为华氏温度的简单程序中应用这些概念。公式为:F = (C × 9/5) + 32。代码读取输入,将其转换为浮点数,执行计算并打印结果。

celsius = float(input(‘Enter Celsius: ‘))
fahrenheit = (celsius * 9 / 5) + 32
print(str(celsius) + ‘°C is ‘ + str(fahrenheit) + ‘°F’)

This example demonstrates type casting, arithmetic operations, string concatenation, and output formatting – all fundamental skills for the A-Level programming module.

这个例子展示了类型转换、算术运算、字符串连接和输出格式化——这些都是 A-Level 编程模块中的基本技能。

Published by TutorHao | Programming Revision Series | aleveler.com

更多咨询请联系16621398022(同微信)

Comments

屏轩国际教育cambridge primary/secondary checkpoint, cat4, ukiset,ukcat,igcse,alevel,PAT,STEP,MAT, ibdp,ap,ssat,sat,sat2课程辅导,国外大学本科硕士研究生博士课程论文辅导

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Discover more from aleveler.com

Subscribe now to keep reading and get access to the full archive.

Continue reading