Python3 Basic Syntax


Coding

By default, Python 3 source code files are encoded in UTF-8 , and all strings are unicode strings. Of course, you can also specify a different encoding for the source code file:

# -*- coding: cp-1252 -*-

The above definition allows the use of character encodings in the Windows-1252 character set in the source files, and the corresponding suitable languages are Bulgarian, Belarusian, Macedonian, Russian, and Serbian.


Identifier

  • The first character must be a letter in the alphabet or an underscore _ .

  • The other parts of the identifier consist of letters, numbers, and underscores.

  • Identifiers are case sensitive.

In Python 3, I18N can be used as variable names, and non-ASCII identifiers are also allowed.


Python Reserved Words

Reserved words are keywords, and we cannot use them as any identifier names. Python's standard library provides a keyword module that can output all keywords of the current version:

>>> import keyword
>>> keyword.kwlist
['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']

Annotation

Single-line comments in Python begin with # , examples are as follows:

Example (Python 3+)

#!/usr/bin/python3
 
# First comment
print ("Hello, Python!") # Second comment

Execute the above code, the output result is:

Hello , Python ! 

Multi-line comments can use multiple # signs, as well as ''' and """ :

Examples (Python 3+)

#!/usr/bin/python3
 
# First comment
# Second comment
 
'''
Third note
Fourth note
'''
 
"""
Fifth note
Sixth note
"""
print ("Hello, Python!")

Execute the above code, the output result is:

Hello , Python ! 

Line and Indent

The most distinctive feature of Python is the use of indentation to represent code blocks, without the need to use curly braces {} .

The number of indented spaces is variable, but statements in the same code block must contain the same number of indented spaces. Examples are as follows:

Example (Python 3+)


if True:
     print ("True")
else:
     print ("False")

The number of spaces in the indentation number of the last line of the following code is inconsistent, which will cause a runtime error:

Example (Python 3+)

if True:

     print ("Answer")

     print ("True")

else:

     print ("Answer")

   print ("False") # Inconsistent indentation will cause runtime errors

Important: Due to the inconsistent indentation of the above program, an error similar to the following will appear after execution:

 File "test.py", line 6
    print ("False") # Inconsistent indentation will cause runtime errors
                                      ^
IndentationError: unindent does not match any outer indentation level

Multi-line Statement

Python usually writes a statement in one line, but if the statement is very long, we can use the backslash \ to implement a multi-line statement, for example:

total = item_one + \
       item_two + \
       item_three

For multi-line statements in [], {}, or (), there is no need to use a backslash \ , for example:

total = [ 'item_one' , 
'item_two' , 'item_three' ,
'item_four' ,
'item_five' ]

Number Type

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 type in python2.

  • bool (Boolean), such as True.

  • float (floating point number), such as 1.23, 3E-2

  • complex (plural), such as 1 + 2j, 1.1 + 2.2j


String

  • The use of single quotes and double quotes in python is exactly the same.

  • Use triple quotation marks ( ''' or """ ) to specify a multi-line string.

  • Escape character \

  • Backslashes can be used to escape, using r can make backslashes not escaped. . If r"this is a line with \n", \n will be displayed instead of a line break.

  • Concatenate strings literally, such as "this ""is" "string" will be automatically converted to this is string.

  • Strings can be concatenated with the + operator and repeated with the * operator.

  • There are two indexing methods for strings in Python, starting with 0 from left to right, and starting with -1 from right to left.

  • Strings in Python cannot be changed.

  • Python does not have a separate character type, a character is a string of length 1.

  • The grammatical format of string interception is as follows: variable [start position: end position: step length]

word ='string'
sentence = "This is a sentence."
paragraph = """This is a paragraph,
Can be composed of multiple lines """

Example (Python 3+)

#!/usr/bin/python3
 
str='123456789'
 
print(str) # output string
print(str[0:-1]) # output all characters from the first to the penultimate
print(str[0]) # Output the first character of the string
print(str[2:5]) # print the characters starting from the third to the fifth
print(str[2:]) # output all characters starting from the third
print(str[1:5:2]) # Output the characters starting from the second to the fifth and every other character (step 2)
print(str * 2) # output string twice
print(str +'hello') # connection string
 
print('------------------------------')
 
print('hello\nTutorialFish') # Use backslash (\)+n to escape special characters
print(r'hello\nTutorialFish') # Add an r in front of the string to indicate the original string and will not be escaped

Here r refers to raw (raw string), which will automatically escape backslashes, for example:

>>> print('\n') # output blank line

>>> print(r'\n') # output \n
\n
>>>

The output of the above example:

123456789
12345678
1
345
3456789
twenty four
123456789123456789
123456789 hello
------------------------------
hello
TutorialFish
hello\nTutorailFish

Blank Line

A blank line is used to separate functions or methods of a class to indicate the beginning of a new piece of code. The class and function entry are also separated by a blank line to highlight the beginning of the function entry.

Blank lines are different from code indentation. Blank lines are not part of the Python syntax. Do not insert blank lines when writing, and the Python interpreter will run without error. However, the function of the blank line is to separate two sections of code with different functions or meanings, so as to facilitate the maintenance or reconstruction of the code in the future.

Remember: blank lines are also part of the program code.


Waiting for User Input

Execute the following program and wait for user input after pressing the Enter key:

Example (Python 3+)

#!/usr/bin/python3
 
input("\n\nPress enter and exit.")

In the above code, "\n\n" will output two new blank lines before the result is output. Once the user presses the enter key, the program will exit.


Display Multiple Statements on A Same Line

Python can use multiple statements in a same line, using semicolons between statements ; for splitting, the following is a simple example:

Example (Python 3+)

#!/usr/bin/python3
 
import sys; x ='TutorialFish.com'; sys.stdout.write(x +'\n')

Use the script to execute the above code, and the output result is:

TutorialFish.com

Use the interactive command line to execute, the output result is:

>>> import sys; x ='tutorialfish'; sys.stdout.write(x +'\n')
tutorialfish
13

Here, 13 represents the number of characters.


Multiple Statements Form A Code Group

A group of statements with the same indentation constitutes a code block, which we call a code group.

For compound statements such as if, while, def, and class. The first line starts with a keyword and ends with a colon (:). 

One or more lines of code after this line constitute a code group.

We call the first line and the following code group as a clause.

Example

if expression:
   suite
elif expression:
   suite
else:
   suite

Print Output

The default output of print is line break, if you want to achieve no line break, you need to add end="" after the variable :

Example (Python 3+)

#!/usr/bin/python3
 
x="a"
y="b"
# Newline output
print( x)
print( y)
 
print('---------')
# No line break output
print( x, end=" ")
print( y, end=" ")
print()

The execution result of the above example is:

a
b
---------
a b

import and from...import

Use import or from...import to import the corresponding module in python .

Import the entire / some module in the format: import somemodule

Import a function from a module, the format is: from somemodule import somefunction

Import multiple functions from a module, the format is: from somemodule import firstfunc, secondfunc, thirdfunc

Import all functions in a module, the format is: from somemodule import *

Import sys module

import sys
print('================Python import mode==========================')
print ('Command line parameters are:')
for i in sys.argv:
     print (i)
print ('\n python path is',sys.path)


Import the argv and path of the sys module

from sys import argv,path # import specific members
 
print('================python from import=========================== =======')
print('path:',path) # Because the path member has been imported, there is no need to add sys.path when quoted here



Command Line Parameters

Many programs can perform some operations to view some basic information. Python can use the -h parameter to view the 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 we execute Python script, we can receive the parameters input from the command line. For specific usage, please refer to the Python 3 command line parameters .