The Ython language has many similarities with languages such as Perl, C, and Java. However, there are some differences.
In this chapter we’ll learn the basic Syntax of Python to get you started programming in Python quickly.
The first Python program
Interactive programming
Interactive programming does not require the creation of script files, but code is written through the interactive mode of the Python interpreter. Finally, if your time is not very tight, and you want to improve quickly, the most important thing is not to be afraid of hardship, I suggest you contact Wei: Mengy7762, that is really good, many people make rapid progress, you need to be afraid of hardship! You can go to add to see ~
On Linux, you just need to enter the Python command on the command line to start the interactive programming, the following window is displayed:
$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.\
\
The interactive programming client has been installed when you install Python on Windows.
Enter the following text at the Python prompt, and press Enter to see how it works:
>>> print ("Hello, Python!" )Copy the code
In Python 2.7.6, the output of the above example is as follows:
Hello, Python!
Copy the code
Scripted programming
The interpreter is called with the script arguments to start executing the script until it finishes executing. When the script is executed, the interpreter is no longer valid.
Let’s write a simple Python script. All Python files will have the.py extension. Copy the following source code to the test.py file.
print ("Hello, Python!" )Copy the code
Here, it is assumed that you have set the Python interpreter PATH variable. Run the program with the following command:
$ python test.py
Copy the code
Output results:
Hello, Python!
Copy the code
Let’s try another way to execute Python scripts. Modify the test.py file to look like this:
The instance
#! /usr/bin/python print (“Hello, Python!” ) \
Here, assuming your Python interpreter is in /usr/bin, execute the script with the following command:
$chmod +x test.py # Add executable permission to script file $./test.pyCopy the code
Output results:
Hello, Python!
Copy the code
Python2.x uses the print function of PYTHon3.x
If python2.x version wants to use the print function that uses PYTHon3.x, you can import the Future package that disables the print statement of PYTHon2.x and uses the print function of python3.x:
The instance
List =[“a”, “b”, “c”] print list # python2.x
[‘a’, ‘b’, ‘c’]\
From future import print_function # Import future package print list # python2.x print statement is disabled
File “”, line 1
print list
^
SyntaxError: invalid syntax\
Print (list) # use python3.x print function \
[‘a’, ‘b’, ‘c’]\
\
Many of the features designed for python3.x compatibility with Python2.x can be imported through the future package.
Python identifier
In Python, identifiers are composed 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 that begin with an underscore have special meaning. A class attribute that begins with a single underscore _foo represents a class attribute that is not directly accessible. It must be accessed through the interface provided by the class and cannot be imported using from XXX import *.
__foo, which begins with a double underline, represents the private member of the class. Finally, if you are not too short of time and want to improve quickly, the most important thing is not to be afraid of hard work, I suggest you contact Wei: Mengy7762, which is really good, many people make rapid progress, you need to be afraid of hard work! If you want to go ahead and add it, look at the fact that foo starts and ends with a double underscore, which is a special method identifier in Python, like init(), which is a class constructor. Finally, if your time is not very tight, and you want to improve quickly, the most important thing is not to be afraid of hardship, I suggest you contact Wei: Mengy7762, that is really good, many people make rapid progress, you need to be afraid of hardship! You can go and add it
Python can display multiple statements on the same line by using a semicolon. Separate, as:
>>> print ('hello'); print ('runoob'); hello runoobCopy the code
Python reserved characters
The following list shows reserved words in Python. These reserved words cannot be used as constants or variables, or any other identifier names.
All Python keywords contain lowercase letters only.
‘
Line and indent
One of the biggest differences between learning Python and other languages is that Python code blocks don’t use curly braces ({}) to control classes, functions, and other logical decisions. One of python’s most distinctive features is the use of indentation to write modules.
The amount of indented white space is variable, but all block statements must contain the same amount of indented white space. This must be strictly enforced.
The following instance is indented with four Spaces:
The instance
if True:
print (“True”)
else:
print (“False”)\
The following code will execute in error:
The instance
#! /usr/bin/python\
–– coding: UTF-8 –– \
File name: test.py\
If True: print (“Answer”) print (“True”) else: print (“Answer”
When executing the above code, the following error notification will appear:
File "test.py", line 11
print ("False")
^
IndentationError: unindent does not match any outer indentation level
Copy the code
IndentationError: unindent does not match any outer indentation level Indententation error:
If IndentationError: unexpected indent error, then the Python compiler is telling you “Hi, buddy, you have an incorrect format in your file, possibly TAB and space misalignments. “All Python has very strict formatting requirements.
Therefore, you must use the same number of indented Spaces at the beginning of lines in Python code blocks. Finally, if your time is not very tight, and you want to improve quickly, the most important thing is not to be afraid of hardship, I suggest you contact Wei: Mengy7762, that is really good, many people make rapid progress, you need to be afraid of hardship! You can go to add to see ~
It is recommended that you use a single TAB or two or four Spaces for each indentation level, but do not mix them
Multi-line statement
Python statements usually end with a new line.
However, we can use a slash (\) to divide a single statement into multiple lines, as shown below:
total = item_one + \
item_two + \
item_three
Copy the code
Statements containing [], {}, or () parentheses do not require multi-line hyphens. Here is an example:
days = ['Monday', 'Tuesday', 'Wednesday',
'Thursday', 'Friday']
Copy the code
Python quotes
Python can use quotation marks (‘), double quotation marks (“), triple quotation marks (‘ “‘, or “””) to represent strings. The beginning and end of quotation marks must be of the same type.
Three quotes can consist of multiple lines, a shortcut syntax for writing multiple lines of text, often used in docstrings, and used as comments at certain points in a file.
Word = 'word' sentence = "This is a sentence." Paragraph = "" this is a paragraph. Contains multiple statements """Copy the code
Python annotation
Single-line comments in Python begin with #.
The instance
#! /usr/bin/python\
–– coding: UTF-8 –– \
File name: test.py\
\
The first comment \
print (“Hello, Python!” ) # Second comment \
Output results:
Hello, Python!
Copy the code
Comments can be made at the end of a statement or expression line:
Name = "Madisetti" # This is a commentCopy the code
Multiline comments in Python use either three single quotes (“””) or three double quotes (“””).
The instance
#! /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 quotes. This is a multi-line comment, with double quotes. This is a multi-line comment, with double quotes. “” \”
Python is a blank line
Blank lines are used between functions or methods of a class to indicate the start of a new section of code. Class and function entries are also separated by a blank line to highlight the beginning of the function entry.
Unlike code indentation, blank lines are not part of Python syntax. Write without inserting blank lines, and the Python interpreter runs without error. But empty lines are used to separate two pieces of code with different functions or meanings, making it easier to maintain or refactor the code later.
Remember: blank lines are also part of the program code.
Waiting for user input
The following program will wait for user input after execution, and press enter to exit:
#! /usr/bin/python # -* -coding: utf-8 -* -raw_input \n")Copy the code
In the above code, \n implements a newline. Once the user presses the Enter key to exit, other keys are displayed.
Multiple statements are displayed on the same line
Python can use multiple statements on the same line, using semicolons (;) between statements. Partition, here is a simple example:
#! /usr/bin/python import sys; x = 'runoob'; sys.stdout.write(x + '\n')Copy the code
Execute the above code and enter:
$ python test.py
runoob
Copy the code
The print output
Print uses a newline by default. If you want to do this, put a comma at the end of the variable.
The instance
#! /usr/bin/python\
–– coding: UTF-8 –– \
x=”a”
y=”b”\
Newline output \
print x
print y
print ‘———‘\
Output \ without a newline
print x,
print y,
\
Output \ without a newline
print x,y\
The execution result of the above example is:
a
b
---------
a b a b
Copy the code
Multiple statements form a code group
A set of statements with the same indent form a block of code called a code group.
For complex statements such as if, while, def, and class, the first line begins with a keyword and ends with a colon (:), and the next line or lines form a code group.
We call the first line and the group of code that follows a clause.
Here is an example:
if expression :
suite
elif expression :
suite
else :
suite
Copy the code
Command line arguments
Many programs can perform operations to see some basic information. Python can use the -h parameter to see help information about 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. ]
Copy the code
When executing Python as a script, you can receive arguments from the command line, as described in [Python Command Line Arguments].