Python3 basic syntax,
Encoding
By default, the Python3 source file is UTF-8 encoded. All strings are unicode strings. You can also specify encoding for the source file.
# -*- coding: cp-1252 -*-
Identifier
- The first character must be a letter or underscore '_' in the alphabet '_'.
- Other parts of an identifier are composed of letters, numbers, and underscores.
- The identifier is case sensitive.
Python Reserved Words
Reserved Words are keywords. We cannot use them as any identifier names. The standard Python Library provides a keyword module that can output all the keywords of the current version:
>>> import keyword>>> keyword.kwlist['False', 'None', 'True', 'and', 'as', 'assert', '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']
Note
In Python, single-line comments start with #. Multiple comments are enclosed by three single quotes (''') or three double quotes.
Line and indent
Python uses indentation to represent code blocks. The number of indented spaces is variable, but the statement of the same code block must contain the same number of indented spaces.
Data Type
Python has four types of numbers: integer, long integer, floating point, and plural.
- Integer, such as 1
- A long integer is a relatively large integer.
- Floating Point Numbers, such as 1.23 and 3E-2
- The plural values include 1 + 2j and 1.1 + 2.2j.
String
- In python, single quotes and double quotes are identical.
- You can use three quotation marks (''' or ") to specify a multi-line string.
- Escape Character '\'
- Natural string, by adding r or R before the string. For example, if r "this is a line with \ n", \ n is displayed, not a line break.
- Python allows you to process unicode strings with the prefix u or U, such as u "this is an unicode string ".
- The string is unchangeable.
- Cascade strings literally. For example, "this" "is" "string" is automatically converted to this is string.