Python Environment Variables: Basic Syntax of Python3
Encoding
By default, Python 3 source files are encoded in UTF-8, and all strings are Unicode strings. However, you can specify a different encoding for the source file:
# -*- coding: cp-1252 -*-
The above definition allows the use of characters from the Windows-1252 character set, which corresponds to languages such as Bulgarian, Belarusian, Macedonian, Russian, and Serbian.
Identifiers
The first character must be a letter from the alphabet or an underscore (
_
).The remaining characters can be letters, numbers, or 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, also known as keywords, cannot be used as any identifier names. Python’s standard library provides a keyword
module that can output all the current version’s keywords:
>>> 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 #
, as shown in the example below:
Example (Python 3.0+)
#!/usr/bin/python3 # First comment print("Hello, Python!") # Second comment
The output of the above code is:
Hello, Python!
Multi-line comments can be made using multiple #
symbols, or with '''
and """
:
Example (Python 3.0+)
#!/usr/bin/python3 # First comment # Second comment ''' Third comment Fourth comment ''' """ Fifth comment Sixth comment """ print("Hello, Python!")
The output of the above code is:
Hello, Python!
Lines and Indentation
One of Python's most distinctive features is the use of indentation to represent code blocks. Curly braces {}
are not used.
The number of spaces for indentation is variable, but all statements in the same block must have the same indentation level, as shown below:
Example (Python 3.0+)
if True: print("True") else: print("False")
Inconsistent indentation will result in an error:
Example
if True: print("Answer") print("True") else: print("Answer") print("False") # Inconsistent indentation will cause an error
The code will raise an error due to inconsistent indentation, similar to this:
File "test.py", line 6 print("False") # Inconsistent indentation will cause an error ^ IndentationError: unindent does not match any outer indentation level
Multi-Line Statements
Python usually writes one statement per line, but if a statement is long, you can use a backslash () to break it into multiple lines, for example:
total = item_one + item_two + item_three
For statements inside []
, {}
, or ()
, a backslash is not required:
total = ['item_one', 'item_two', 'item_three', 'item_four', 'item_five']
Number Types
Python has four types of numbers: integers, booleans, floats, and complex numbers.
int
: integer type, e.g.,1
. In Python 3, there's only one integer type,int
, with nolong
type like in Python 2.bool
: boolean type, e.g.,True
.float
: floating point numbers, e.g.,1.23
,3E-2
.complex
: complex numbers, represented asa + bj
, wherea
is the real part,b
is the imaginary part, andj
is the imaginary unit. For example,1 + 2j
or1.1 + 2.2j
.
Strings
In Python, single quotes '
and double quotes "
are treated the same.
Triple quotes (
'''
or"""
) allow multi-line strings.Escape character: .
The backslash can be used to escape characters; using
r
prevents escaping. For example,r"this is a line with "
will display instead of a newline.Literal concatenation is possible, such as
"this " "is " "a string"
, which automatically converts tothis is a string
.Strings can be concatenated with the
+
operator and repeated with the*
operator.Strings in Python are indexed from 0 for the first character and -1 for the last character.
Python strings are immutable.
Strings can be sliced using
str[start:end]
, wherestart
is inclusive andend
is exclusive.String slices can include a step parameter in the format
str[start:end:step]
.
Example (Python 3.0+)
#!/usr/bin/python3 str = '123456789' print(str) # Output the entire string print(str[0:-1]) # Output all characters except the last one print(str[0]) # Output the first character print(str[2:5]) # Output characters from index 2 to 4 print(str[2:]) # Output characters from index 2 onwards print(str[1:5:2]) # Output every second character from index 1 to 4 print(str * 2) # Output the string twice print(str + 'hello') # Concatenate the string with "hello" print('------------------------------') print('hello runoob') # Using a backslash () + n to escape special characters print(r'hello runoob') # Add an r to prevent escaping in the string
The output is:
123456789 12345678 1 345 3456789 24 123456789123456789 123456789hello ------------------------------ hello runoob hello runoob
In raw strings (indicated by r
), backslashes are not escaped. For example:
>>> print(' ') # Outputs a blank line >>> print(r' ') # Outputs
Blank Lines
Blank lines are used to separate sections of code and indicate the start of a new section. For instance, they can be placed between function definitions or class methods.
While blank lines are not a part of Python syntax, they help separate code with different functions or purposes, making it easier to maintain or refactor the code.
Waiting for User Input
The following code waits for the user to press the enter key before exiting:
Example (Python 3.0+)
#!/usr/bin/python3 input(" Press the enter key to exit.")
In the above code, will output two new lines before the input prompt. The program will exit after the user presses the enter key.
Displaying Multiple Statements on the Same Line
Python allows multiple statements on the same line by using a semicolon (;
) to separate them. Here’s an example:
Example (Python 3.0+)
#!/usr/bin/python3 import sys; x = 'runoob'; sys.stdout.write(x + ' ')
When the script is executed, the output is:
runoob
In the interactive mode:
>>> import sys; x = 'runoob'; sys.stdout.write(x + ' ') runoob 7
The 7
represents the number of characters in runoob
(6 characters) and (1 character), totaling 7 characters.
Code Blocks
A group of statements with the same indentation level forms a code block. This is often seen in compound statements such as if
, while
, def
, and class
, where the first line starts with a keyword and ends with a colon (:
). The following lines make up the code block or clause.
For example:
if expression: suite elif expression: suite else: suite
Print Output
By default, print
outputs a newline after each call. To prevent this and print without a newline, add end=""
at the end of the variable:
Example (Python 3.0+)
#!/usr/bin/python3 x = "a" y = "b" # Output with newline print(x) print(y) print('---------') # Output without newline print(x, end=" ") print(y, end=" ") print()
The output is:
a b --------- a b
Import and from...import
In Python, you can use import
or from...import
to import the appropriate module.
To import an entire module (somemodule), the format is:
import somemodule
To import a specific function from a module, the format is:
from somemodule import somefunction
To import multiple functions from a module, the format is:
from somemodule import firstfunc, secondfunc, thirdfunc
To import all functions from a module, the format is:
from somemodule import *
Importing the sys
module
import sys print('================Python import mode==========================') print('Command line arguments are:') for i in sys.argv: print(i) print(' Python path is', sys.path)
Importing specific members (argv
, path
) from the sys
module
from sys import argv, path # Import specific members print('================Python from import==========================') print('path:', path) # Since `path` has been imported, no need to use `sys.path` here
For more details, you can refer to: The main difference between import
and from...import
.
Command Line Arguments
Many programs can perform specific operations to check some basic information. Python can use the -h
argument to check help information for all options:
$ 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 we execute Python in script form, we can receive command-line input parameters.