Python basic syntax

Python basic syntax

Python
Basic syntax
The Python language has many similarities with languages such as Perl, C, and Java. However, there are some differences.
In this chapter, we will learn the basic syntax of Python in the future, so that you can quickly learn Python programming.
Interactive programming of the first Python program
Interactive programming does not need to create a script file, and code is written through the interactive mode of the Python interpreter.
On linux, you only need to enter the Python command in the command line to start interactive programming. The prompt window is as follows:
$ python
Python
2.7
.
6
(
default
,
Sep
9
2014
,
15
:
04
:
36
)
[
GCC
4.2
.
1
Compatible
Apple
LLVM
6.0
(
clang
-
600.0
.
39
on darwin
Type
"help"
,
"copyright"
,
"credits"
or
"license"
for
more information
.
>>>
When installing Python on Window, an interactive programming client has been installed, and the prompt window is as follows:
Enter the following text information in the python prompt, and then press Enter to view the running effect:
>>>
print
"Hello, Python!"
In Python 2.7.6, the output of the above example is as follows:
Hello
,
Python
!
Scripted programming
Call the interpreter through the script parameters to start the script execution until the script execution is completed. When the script execution is complete, the interpreter is no longer valid.
Let's write a simple Python script program. All Python files will have a .py extension. Copy the following source code to the test.py file.
print
"Hello, Python!"
Here, it is assumed that you have set the Python interpreter PATH variable. Run the program with the following command:
$ python test
.
py
Output result:
Hello
,
Python
!
Let's try another way to execute Python scripts. Modify the test.py file as follows:
#!/usr/bin/python
print
"Hello, Python!"
Here, assuming that your Python interpreter is in the/usr/bin directory, use the following command to execute the script:
$ chmod
+
x test
.
py
# Add executable permissions to script files
$
./
test
.
py
Output result:
Hello
,
Python
!
Python identifier
In Python, identifiers consist of letters, numbers, and underscores.
In Python, all identifiers can include English, numbers, and underscores (_), but cannot start with a number.
Identifiers in Python are case sensitive.
Identifiers beginning with an underscore have a special meaning. The _foo that starts with a single underscore represents class attributes that cannot be directly accessed. They need to be accessed through the interface provided by the class, and cannot be imported with from xxx import *.
__Foo starting with a double underscore represents a private member of the class, and __foo__ starting and ending with a double underscore represents a special method-specific identifier in Python, for example, __init__() represents the constructor of the class.
Python can display multiple statements on the same line by using a semicolon; to separate them, such as:
>>>
print
'hello'
;
print
'runoob'
;
hellorunoob
Python reserved characters
The following list shows the reserved words in Python. These reserved words cannot be used as constants or variables, or any other identifier names.
All Python keywords only contain lowercase letters.
andexecnot
assertfinallyor
breakforpass
classfromprint
continueglobalraise
defifreturn
delimporttry
elifinwhile
elseiswith
exceptlambdayield
Line and indent
The biggest difference between learning Python and other languages is that Python code blocks do not use curly braces {} to control classes, functions, and other logical judgments. The most distinctive feature of Python is to use indentation to write modules.
The amount of white space indented is variable, but all code block statements must contain the same amount of white space indented. This must be strictly enforced. As follows:
if
True
:
print
"True"
else
:
print
"False"
The following code will execute an error:
#!/usr/bin/python
# -*- coding: UTF-8 -*-
# File name: test.py
if
True
:
print
"Answer"
print
"True"
else
:
print
"Answer"
# There is no strict indentation, an error will be reported during execution
print
"False"
When the above code is executed, the following error message will appear:
$ python test
.
py
File
"test.py"
,
line
10
print
"False"
^
IndentationError
:
unindent does
not
match any outer indentation level
IndentationError: unindent does not match any outer indentation level error indicates that the indentation method you use is inconsistent, some are tab key indentation, and some are space indentation, just change it to the same.
If it is an IndentationError: unexpected indent error, the python compiler is telling you "Hi, man, the format in your file is wrong, it may be the problem of misalignment of tabs and spaces". All pythons have very strict requirements on the format.
Therefore, the same number of indented spaces must be used in Python code blocks.
We suggest you use for each indentation level of a single tab or two spaces or four spaces , remember not to mix
Multi-line statement
In Python statements, a new line is generally used as the end of the statement.
But we can use a slash (\) to divide a line of statements into multiple lines for display, as shown below:
total
=
item_one
+
/item_two
+
/item_three
If the statement contains [], {} or () brackets, there is no need to use multi-line connectors. Examples are as follows:
days
=
[
'Monday'
,
'Tuesday'
,
'Wednesday'
,
'Thursday'
,
'Friday'
Python quotes
Python can use quotation marks ( ' ), double quotation marks ( " ), and triple quotation marks ( ''' or """ ) to denote strings. The beginning and end of the quotation marks must be of the same type.
The triple quotation marks can be composed of multiple lines. It is a shortcut syntax for writing multiple lines of text. It is often used in docstrings and is used as a comment in a specific place in a file.
word
=
'word'
sentence
=
"This is a sentence."
paragraph
=
"""This is a paragraph. Contains multiple sentences """
Python notes
Single-line comments in python start with #.
#!/usr/bin/python
# -*- coding: UTF-8 -*-
# File name: test.py
# First comment
print
"Hello, Python!"
# 2.comment
Output result:
Hello
,
Python
!
The comment can be at the end of a statement or expression line:
name
=
"Madisetti"
# This is a comment
Multi-line comments in python use three single quotation marks (''') or three double quotation marks (""").
#!/usr/bin/python
# -*- coding: UTF-8 -*-
# File name: test.py
'''This is a multi-line comment, using single quotes. This is a multi-line comment, using single quotes. This is a multi-line comment, using single quotes. '''
"""This is a multi-line comment, using double quotation marks. This is a multi-line comment, using double quotation marks. This is a multi-line comment, using double quotation marks. """
Python 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. But the function of the blank line is to separate two sections of code with different functions or meanings to facilitate future code maintenance or reconstruction.
Remember: blank lines are also part of the program code.
Waiting for user input
After the following program is executed, it will wait for user input and exit after pressing the Enter key:
#!/usr/bin/python
# -*- coding: UTF-8 -*-
raw_input
(
"Press enter to exit, any other key will display...\n"
)
In the above code,/n implements line break. Once the user presses the enter key to exit, the other keys are displayed.
Display multiple statements on the same line
Python can use multiple statements in the same line, separated by semicolons (;) between statements. The following is a simple example:

#!/usr/bin/python
import
sys
;
x
=
'runoob'
;
sys
.
stdout
.
write
(
x
+
'\n'
)
Execute the above code, the input result is:
$ python test
.
pyrunoob
Print output
The default output of print is line break, if you want to achieve no line break, you need to add a comma at the end of the variable,
#!/usr/bin/python
# -*- coding: UTF-8 -*-
x
=
"a"
y
=
"b"
# Newline output
print
x
print
y
print
'---------'
# No line break output
print
x
,
print
y
,
# No line break output
print
x
,
y
The execution result of the above example is:
ab
---------
abab
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 like if, while, def, and class, the first line starts with a keyword and ends with a colon (: ), and one or more lines of code after this line constitute a code group.
We call the first line and the following code group a clause.
Examples are as follows:
if
expression
:
suite
elif
expression
:
suite
else
:
suite
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 in the form of a script, we can receive the parameters input from the command line. For specific usage, please refer to .


Shared from rookie tutorial

For more technical information, please pay attention to: itheimaGZ