Python 3 basic syntax
Python 3 Basic Syntax
Encoding
By default, Python 3 source code files are encoded in UTF-8, and all strings are Unicode.
Of course, you can also specify a different encoding for your source code files:
# -*- coding: cp-1252 -*-
The above definition allows the use of character encodings in the Windows-1252 character set in source files, which is suitable for languages such as Bulgarian, Belarusian, Macedonian, Russian, and Serbian.
Identifiers
- The first character must be a letter of the alphabet or an underscore (_).
- The rest of the identifier may consist of letters, numbers, and underscores.
- Identifiers are case-sensitive.
In Python 3, you can use Chinese characters as variable names, and non-ASCII identifiers are also allowed.
Python Reserved Words
Reserved words are keywords and cannot be used as identifier names. Python’s standard library provides a keyword module that prints all keywords for 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']
Comments
Single-line comments in Python begin with #. Examples are as follows:
Example (Python 3.0+)
#!/usr/bin/python3
# First comment
print ("Hello, Python!") # Second comment
Executing the above code will output:
Hello, Python!
Multi-line comments can use multiple # signs, as well as “‘” and “””:
Example (Python 3.0+)
#!/usr/bin/python3
# First comment
# Second comment
'''
Third comment
Fourth comment
'''
"""
Fifth comment
Sixth comment
"""
print ("Hello, Python!")
Executing the above code will output:
Hello, Python!
Lines and Indentation
Python’s most distinctive feature is its use of indentation to denote code blocks, eliminating the need for curly braces {}.
The number of spaces indented can vary, but statements within the same code block must contain the same number of spaces indented. The following example is as follows:
Example (Python 3.0+)
if True:
print ("True")
else:
print ("False")
The following code has inconsistent indentation numbers for the last line of the statement, which will result in a runtime error:
if True:
print ("Answer")
print ("True")
else:
print ("Answer")
print ("False") # Inconsistent indentation will result in a runtime error
Due to inconsistent indentation, the above program will produce an error similar to the following after execution:
File "test.py", line 6
print ("False") # Inconsistent indentation will result in a runtime error
^
IndentationError: unindent does not match any outer indentation level
Multi-line Statements
Python usually writes a statement on a single line, but if the statement is long, we can use backslashes () to implement multi-line statements. For example:
total = item_one +
item_two +
item_three
Multi-line statements within [], {}, or () do not require backslashes (). For example:
total = ['item_one', 'item_two', 'item_three',
'item_four', 'item_five']
Number Types
There are four types of numbers in Python: integers, Booleans, floating-point numbers, and complex numbers.
- int (integer), such as 1. There is only one integer type, int, which is represented as a long integer; there is no Long in Python 2.
- bool (Boolean), such as True.
- float (floating-point number), such as 1.23 and 3E-2.
- complex (complex number), such as 1 + 2j and 1.1 + 2.2j.
String
- Single and double quotes are used identically in Python.
- Multi-line strings can be specified using triple quotes (“‘ or “””).
- Escape character ”
- Backslash can be used to escape characters. Using ‘r’ prevents backslashes from being escaped. For example, if you write r”this is a line with n”, n will be displayed, not a line break.
- Concatenating strings literally, such as “this”, “is”, “string”, will automatically be converted to “this is string”.
- Strings can be concatenated using the + operator and repeated using the * operator.
- Strings in Python have two indexing methods: starting at 0 from the left and starting at -1 from the right.
- Strings in Python cannot be modified.
- Python does not have a separate character type; a character is a string of length 1.
- The syntax for string truncation is as follows: variable [head subscript: tail subscript: step length]
word = 'string'
sentence = "This is a sentence."
paragraph = """This is a paragraph,
can consist of multiple lines."""
Example (Python 3.0+)
#!/usr/bin/python3
str='Geekdoc'
print(str) # Output string
print(str[0:-1]) # Output all characters from the first to the second-to-last
print(str[0]) # Output the first character of the string
print(str[2:5]) # Output characters from the third to the fifth
print(str[2:]) # Output all characters from the third to the last
print(str * 2) # Outputs a string twice
print(str + '你好') # Concatenates strings
print('------------------------------')
print('hellongeekdoc') # Use backslash ()+n to escape special characters
print(r'hellongeekdoc') # Add an r to the beginning of the string to indicate a raw string, without escaping.
Here, r stands for raw, i.e., raw string.
The output is:
Geekdoc
Geekdo
G
ekd
ekdoc
GeekdocGeekdoc
Geekdoc你好
------------------------------
hello
geekdoc
hellongeekdoc
Blank Lines
Blank lines separate functions or class methods to indicate the beginning of a new section of code. Class and function entry points are also separated by a blank line to highlight the beginning of a function entry point.
Blank lines, unlike code indentation, are not part of Python syntax. The Python interpreter will run without errors even if you don’t insert blank lines when writing. However, blank lines serve to separate two sections of code with different functions or meanings, making them easier to maintain or refactor later.
Remember: Blank lines are also part of the program code.
Waiting for User Input
Executing the following program will wait for user input after pressing the Enter key:
Example (Python 3.0+)
#!/usr/bin/python3
input("nn Press Enter to exit.")
In the above code, “nn” will output two new blank lines before the result. Once the user presses Enter, the program will exit.
Displaying Multiple Statements on the Same Line
Python allows you to use multiple statements on the same line, separated by semicolons (;). The following is a simple example:
Example (Python 3.0+)
#!/usr/bin/python3
import sys; x = 'geekdoc'; sys.stdout.write(x + 'n')
Executing the above code using a script will produce the following output:
geekdoc
Executing the above code using an interactive command prompt will produce the following output:
>>> import sys; x = 'geekdoc'; sys.stdout.write(x + 'n')
geekdoc
7
The 7 here represents the number of characters.
Multiple statements form a code group
A group of statements with the same indentation forms a code block, which is called a code group.
Compound statements like if, while, def, and class begin with a keyword on the first line and end with a colon (:). The following line of code, followed by one or more lines of code, constitute a code group.
The first line and the following code group are called a clause.
Example below:
if expression:
suite
elif expression:
suite
else:
suite
Print Output
The default output of print is line-wrapped. To prevent line-wrapping, add end=”” to the end of the variable:
Example (Python 3.0+)
#!/usr/bin/python3
x="a"
y="b"
# Line-wrapped output
print( x )
print( y )
print('---------')
# Line-wrapped output
print( x, end=" " )
print( y, end=" " )
print()
The above example produces the following results:
a
b
---------
a b
Import and from…import
In Python, use import or from…import to import the corresponding module.
Import the entire module (somemodule) using the following format: import somemodule
Import a function from a module using the following format: from somemodule import somefunction
Import multiple functions from a module using the following format: from somemodule import firstfunc, secondfunc, thirdfunc
Import all functions from a module using the following format: from somemodule import *
Import the sys module
import sys
print('================Python import mode========================')
print('Command line arguments are:')
for i in sys.argv:
print(i)
print('n python The path is ',sys.path)
Import the argv,path members of the sys module
from sys import argv,path # Import specific members
print('================python from import====================================')
print('path:',path) # Because the path member has already been imported, there's no need to add sys.path when referencing it here.
Command Line Parameters
Many programs allow you to perform operations to view basic information. Python can use the -h parameter to view help information for each parameter:
$ python -h
usage: python [option] ... [-c cmd | -m mod | file | -] [arg] ...
Options and arguments (and corresponding environment variables):
-c cmd : program passed in as string (terminates option list)
-d : debug output from parser (also PYTHONDEBUG=x)
-E : ignore environment variables (such as PYTHONPATH)
-h : print this help message and exit
[ etc. ]
When executing Python as a script, we can accept command-line arguments.