Identifiers and Kewyords
Identifiers are names given by programmers to variables, functions, attributes, and other objects.
Identifier Naming Rules
- Case-sensitive:
acd,ACD, andacDare all different identifiers. - Start with a letter or underscore: Must begin with a letter (
a-z,A-Z) or underscore_, but not a digit. For example,acdand_acdare valid, while3acdis not. - Subsequent characters: Can be letters, digits, or underscores.
- Avoid reserved words: Keywords and built-in function names cannot be used as identifiers.
- Special names: Identifiers starting and ending with double underscores have special meaning in Python; avoid using them unless necessary.
Common Naming Conventions in Practice
| Element | Convention |
|---|---|
| Module, Package | All lowercase with underscores between words |
| Function | All lowercase with underscores between words |
| Class | CapWords (CamelCase), e.g., MyClassTest |
| Constant | All uppercase with underscores between words |
Discovering Keywords
Method 1: In PyCharm, run:
help()
Then type keywords in the help> prompt.
Method 2: Execute the following code:
import keyword
print(keyword.kwlist)
Output:
['False', 'None', 'True', 'and', 'as', 'assert', 'async', 'await', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise', 'return', 'try', 'while', 'with', 'yield']
Comments
Comments are text ignored by the Python interpreter, used for code explanation.
Single-line Comment
Use # before the comment text. In PyCharm, shortcut: Ctrl + /.
Multi-line Comment
Enclose text between three single quotes ''' or three double quotes """. This is technically a string literal, but if not assigned to a variable, it acts as a comment and is eventually garbage-collected.
Varialbes and Constants
Variables
Python does not require explicit type declaration. A variable is created when a value is assigned to an identifier. The variable's type is determined by the assigned value.
y = 20
y = True # y now holds a boolean value
Deleting Variables
Use the del statement to remove a variable. After deletion, accessing it raises a NameError.
x = 10
del x
print(x) # NameError: name 'x' is not defined
A variable must be declared before use. If an object has no references, it becomes eligible for garbage collection.
Constants
Python lacks a syntactic way to define true constants. By convention, variables are treated as constants and should not be modified after assignment.
Statements
A single line of code forms a statement. Semicolons are optional.
Chained Assignment
a = b = c = 10 # 10 assigned to a, b, and c
Series Unpacking Assignment
a, b, c = 10, 20, 30
print(a, b, c) # Outputs: 10 20 30
Variable Swapping
Python allows swapping values without a temporary variable:
x, y = 100, 300
x, y = y, x
print(x, y) # Outputs: 300 100
Line Continuation with Backslash
Long lines can be split using \:
text = "abcdefghijkl\
mnopqrstuv\
wxyzaaaaa"
print(text)
Output:
abcdefghijklmnopqrstuvwxyzaaaaa
Indentation
Python uses indentation to define code blocks, similar to braces {} in C-like languages. Consistent indentation is required.
- Any number of spaces is allowed, but must be consistent within a block.
- In PyCharm, pressing
Tabinserts 4 spaces. - Do not mix tabs and spaces.
Modules
A module is a .py file containing Python code. It is the smallest unit of code organization. A Python program executes statements in a module sequentially.
Importing a Module
Approach 1: Import entire module
import module_name
# usage: module_name.function()
Approach 2: Import specific elements
from module_name import function_name
# usage: function_name()
Packages
Packages help organize modules and avoid name conflicts.
Creating a Package
In the project, right-click → New → Python Package, then enter a name. A package always contains an __init__.py file (can be empty) to signal to the interpreter that the directory is a package.
Importing a Package
import com.hello as a
# usage: a.function_name()
This imports all code elements from the com.hello module, aliased as a.