Click the blue word "python tutorial" to follow us!
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.
The first Python program
Interactive programming
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. >>> ''' In the learning process, if you don’t know anything, you can add my python learning exchange button qun, 934109170 There are good learning tutorials, development tools and e-books in the group. Share with you the current talent needs of python companies and how to learn python from a zero basis, and what to learn. '''
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 see the running effect:
>>> print "Hello, Python!"
In Python 2.7.6 version, the output of the above example is as follows:
Scripted programming
Call the interpreter through the script parameters to start the script execution until the script execution is completed. When the script is executed, 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:
Let's try another way to execute Python scripts. Modify the test.py file as follows:
Instance
#!/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, which must 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, such as __init__() for the constructor of the class.
Python can display multiple statements on the same line by using semicolons; to separate them, such as:
>>> print'hello';print'runoob'; hello runoob
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.
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, and this must be strictly enforced. As follows:
Instance
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 reminder 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.
It is recommended that you use a single tab or two spaces or four spaces at each indentation level, and remember not to mix them
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 can use quotation marks ('), double quotation marks ("), and triple quotation marks (''' or """) to represent 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 at a specific location in a file.
word ='word' sentence = "This is a sentence." paragraph = """This is a paragraph. Contains multiple sentences """
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:
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 quotes. This is a multi-line comment, using double quotes. This is a multi-line comment, using double quotes. """
Python blank lines
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 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.
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:
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:
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
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 parameters input from the command line. If you don’t understand in the process of learning python crawler, you can leave a message for me, you can pay attention to me, I will share small cases and learning experience about python from time to time
Precautions
01
Students who are interested in Python development technology, welcome to join the communication group below to learn together and discuss with each other.
02
If you don’t understand in the process of learning python, you can join my python zero-base system to learn and exchange Qiuqiu qun: 934109170, to share with you the current talent needs of Python companies and how to learn Python from a zero-base, and what to learn. Related learning video materials and development tools are shared
Alright! The article is shared with the readers here
Finally, if you find it helpful, remember to follow, forward, and favorite