author : Han Xinzi @ShowMeAI
Tutorial address :http://www.showmeai.tech/tutorials/56
This paper addresses :http://www.showmeai.tech/article-detail/66
Statement : copyright , For reprint, please contact the platform and the author and indicate the source
This series of tutorials will explain Python programing language , Before you learn specific grammar knowledge , Let's learn something first Python As a foundation for .
This article will Python Give a brief introduction , By reading this article, you will learn :
Interactive programming does not need to create script files , It's through Python The interpreter's interaction mode comes in to write code .
You just need to type... On the command line Python Command to start interactive programming , The prompt window is as follows :
$ python
Python 3.9.5 (default, May 4 2021, 03:33:11)
[Clang 12.0.0 (clang-1200.0.32.29)] on darwin
Type "help", "copyright", "credits" **or** "license" **for** more information.
>>>
stay python Enter the following text message at the prompt , Then press Enter Key to see the running effect :
>>> print("Hello, ShowMeAI, this is Python!")
In my current Python3.9.5 In the version , The output of the above example is as follows :
Hello, ShowMeAI, this is Python!
You can also use Previous section Mentioned Anaconda In the environment Jupyter Notebook Interactive Python Programming , start-up Jupyter Notebook And new Notebook as follows , You can go to cell Code writing and interaction in .
If the task we need to complete is more complex , We can organize the intermediate processing process into python Script , Then call the interpreter through the script parameters to start executing the script , Until the script is finished . When the script is finished , The interpreter is no longer valid .
Let's write a simple Python Script program . all Python The file will be .py Extension name . Copy the following source code to test.py In file .
print("Hello, ShowMeAI, this is Python!")
Use the following command to run the program :
$ python test.py
Output results :
Hello, ShowMeAI, this is Python!
Identifiers are allowed as variables ( function 、 Class etc. ) A valid string for the name . among , Part of it is keywords ( The identifier reserved by the language itself ), It cannot be used as an identifier for other purposes , Otherwise it will cause syntax errors (SyntaxError abnormal ).Python There is also called built-in Identifier set , Although they are not reserved words , But these special names are not recommended .
Python Is a dynamically typed language , That is, you don't need to declare the type of the variable in advance . The type and value of the variable are initialized at the moment of assignment . Variable assignment is performed by an equal sign .
Python A valid identifier for consists of upper and lower case letters 、 Underline and numbers make up . The number cannot be the first character , The length of the identifier is unlimited ,Python Identifiers are case sensitive .
In programming languages , There are two common ways to name variables :
Hump body :
Underline :
The following list shows in Python Reserved word in . These reserved words cannot be used as constants or variables , Or any other identifier name .
all Python The keyword of contains only lowercase letters .
Study Python The biggest difference from other languages is ,Python The code block of does not use braces {} To control the class , Functions and other logical judgments .python The most characteristic is to use indentation to write modules .
Indent can use tab Or spaces, etc , The number of blanks is variable , But all code block statements must contain the same amount of indented white space .
The following example is indented with four spaces :
if True:
print("True")
else:
print("False")
The following code will execute in error :
#!/usr/bin/python
# -*- coding: UTF-8 -*-
# file name :test.py
if True:
print("ShowMeAI")
print("Awesome")
else:
print("Test")
# There is no strict indentation , Error will be reported during execution
print("False")
Execute the above code , The following error alerts will appear :
File "<stdin>", line 11
print("False")
^
IndentationError: unindent does not match any outer indentation level
Common alignment errors are 2 Kind of :
IndentationError: unindent does not match any outer indentation level
IndentationError: unexpected indent
therefore , stay Python You must use the same number of indented spaces at the beginning of lines in the code block of .
I suggest you in actual programming , Use... For each indentation level Single tab or Two spaces or Four spaces , Remember not to mix
Python In a statement, a new line is usually used as the end of the statement .
But we can use slashes ( \) Divide a line of statements into multiple lines to display , As shown below :
total = item_one + \
item_two + \
item_three
The statement contains [], {} or () Brackets do not need to use multiline connectors . The following example :
days = ['Monday', 'Tuesday', 'Wednesday',
'Thursday', 'Friday']
Python You can use quotation marks ( ' )、 Double quotes ( " )、 Three quotes ( ''' or """ ) To represent a string , The beginning and end of a quotation mark must be of the same type .( More detailed python For string knowledge, see python String and operation )
Three quotation marks can be made up of multiple lines , Write fast syntax for multiline text , Commonly used for document strings , At the specific location of the document , As a comment .
word = 'word'
sentence = " This is a ShowMeAI A tutorial for ."
paragraph = """ This is a multi line statement .
One line contains ShowMeAI"""
python Middle and single line notes use # start .
#!/usr/bin/python
# -*- coding: UTF-8 -*-
# file name :test.py
# The first note
print("Hello, ShowMeAI, this is Python!") # The second note
Output results :
Hello, ShowMeAI, this is Python!
Comments can be at the end of a statement or expression line :
name = "ShowMeAI" # This is a comment
python Use more than three quotes in a single line (''') Or three double quotes (""").
#!/usr/bin/python
# -*- coding: UTF-8 -*-
# file name :test.py
'''
This is a multiline comment , Use single quotes .
This is a multiline comment , Use single quotes .
This is a multiline comment , Use single quotes .
'''
"""
This is a multiline comment , Use double quotes .
This is a multiline comment , Use double quotes .
This is a multiline comment , Use double quotes .
"""
Functions or methods of classes are separated by empty lines , Represents the beginning of a new piece of code . Classes and function entries are also separated by a blank line , To highlight the beginning of the function entry .
Blank lines are not the same as code indentation , Air travel is not Python Part of grammar . Don't insert blank lines when writing ,Python The interpreter will not run wrong . But blank lines are used to separate two pieces of code with different functions or meanings , Easy to maintain or refactor the code in the future .
The following program will wait for user input after execution , Press enter and exit :
#!/usr/bin/python
# -*- coding: UTF-8 -*-
input(" Press down enter Key to exit , Any other key displays ...\n")
In the above code ,\n Implement line break . Once the user presses enter( enter ) Key to exit , Other key display .
Python You can use multiple statements on the same line , Use semicolons... Between statements (;) Division , Here is a simple example :
#!/usr/bin/python
import sys; x = 'ShowMeAI'; sys.stdout.write(x + '\n')
Execute the above code , The input result is :
$ python test.py
ShowMeAI
python3 in print The default output is line feed , If you want to implement no line wrapping, you need to add... At the end of the variable 「, end=''」.
#!/usr/bin/python
# -*- coding: UTF-8 -*-
x="a"
y="b"
# Line feed output
print(x)
print(y)
print('---------')
# Don't wrap output
print(x, end='')
print(y, end='')
# Don't wrap output
print(x, y, end='')
The execution result of the above example is :
a
b
---------
a b a b
Indent the same set of statements into a block of code , We call it code group .
image if、while、def and class Such compound statements , The first line starts with keywords , With a colon ( : ) end , One or more lines of code following this line form a code group .
We call the first and subsequent code groups a clause (clause).
The following example :
if expression :
suite
elif expression :
suite
else :
suite
The code for this tutorial series can be found in ShowMeAI Corresponding github Download , Can be local python Environment is running , You can visit google Your baby can also use google colab One click operation and interactive operation learning Oh !
This tutorial series covers Python The quick look-up table can be downloaded and obtained at the following address :