Every program names things and performs actions on them. The rules for the names, the reserved words of the language and the operators determine how a statement is read.
Identifiers
An identifier is the name given to a variable, function or other object. It may contain letters, digits and the underscore, it must not start with a digit, and it cannot contain spaces or symbols such as @ or -. Names are case sensitive. Good names describe the purpose, such as total_marks. By convention, variable and function names are written in lowercase with underscores.
Keywords
Keywords are reserved words that have a fixed meaning in the language and cannot be used as identifiers. Examples are if, else, while, for, def, class, return, import, True, False and None. The list can be seen with the keyword module.
Definition: Identifier. A user-chosen name for a variable, function, class or module; it must start with a letter or underscore and may contain letters, digits and underscores.
Operators and Precedence
Python has arithmetic operators (+, -, , /, //, %, ), comparison operators (==, !=, <, >, <=, >=), logical operators (and, or, not), assignment operators (=, +=, -=, and others) and membership operators (in, not in). The operator / always gives a float, // gives the floor quotient, % gives the remainder and gives a power. Precedence decides which operator is applied first. Brackets come first, then , then unary minus, then , /, // and %, then + and -, then comparisons, and finally not, and and or. Operators of the same level are evaluated from left to right, except ** which goes from right to left.
Table 1.2: Operator precedence, highest first
| Level | Operators | Note |
|---|---|---|
| 1 | ( ) | Brackets |
| 2 | ** | Right to left |
| 3 | *, /, //, % | Left to right |
| 4 | +, - | Left to right |
| 5 | <, >, ==, != | Comparison |
| 6 | not, and, or | Logical |
Example 1.2: Evaluating an expression
Problem: Evaluate 2 + 3 4 * 2 // 5 - 7 % 4.
Solution:
- 4 * 2 = 16, then 3 16 = 48, then 48 // 5 = 9.
- 7 % 4 = 3.
- 2 + 9 - 3 = 8.
Result: The value of the expression is 8.
print(2 + 3 * 4 ** 2 // 5 - 7 % 4)
print(7 / 2, 7 // 2, 7 % 2, 2 ** 3 ** 2)
import keyword
print(len(keyword.kwlist), keyword.iskeyword("while"))
Output
8
3.5 3 1 512
35 True
Common mistakes
- Starting an identifier with a digit, as in 2name.
- Using a keyword such as class as a variable name.
- Expecting 7 / 2 to give 3. It gives 3.5, and 7 // 2 gives 3.
Key takeaways
- Identifiers are case sensitive and cannot start with a digit.
- Keywords are reserved and cannot be used as names.
- / gives a float, // gives the floor quotient.
- ** is evaluated from right to left.
Practice questions
- What is the value of 7 // 2?
- Name three logical operators.
- Can a keyword be used as an identifier?
Answers to the practice questions
-
- and, or, not.
- No.
Sources
- Official BCA syllabus Python Programming, course code 26BCA403SEC01, Unit I
