程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Basic knowledge of Python

編輯:Python

python Basic knowledge of

author:Once Day date:2022 year 2 month 16 Japan

The purpose of this document is to summarize the relevant contents , Scattered knowledge is difficult to remember and learn .

This document is based on windows platform .

View a full range of documents :python Basics _CSDN Blog .

List of articles

      • python Basic knowledge of
        • 1. Text encoding
        • 2. identifier
        • 3.python Reserved words
        • 4. notes
        • 5. Code indentation
        • 6. Multi line statement
        • 7.import and from...import
        • 8. View help from the command line
        • 9. matters needing attention
          • Recommended references :
          • notes : The content of this article is collected and summarized on the Internet , For learning only !

1. Text encoding

By default python Use UTF-8 code , In memory unicode character string ,python Will automatically complete the conversion process !

You can also specify other codes for the source file :

# -*- coding: GB 2312 -*-

The simplified Chinese coding method is specified above , however Recommended UTF-8 code .

2. identifier

An identifier is a pair of variables 、 Constant 、 function 、 Class and other objects .

python stay Python 3 in , Not ASCII Encoded identifiers are also allowed , Like using Chinese . Here are the naming requirements :

  • The first character must be a letter or underscore in the alphabet ’_’.
  • The rest of the identifier has letters 、 Numbers and underscores .
  • Identifiers are case sensitive .

It is recommended to use identifiers starting with English letters , The beginning of an underscore usually has a meaning .

>>> I love you! python=100
>>> I love you! python
100

You can see python The characters supported by identifiers are quite broad , But this is not recommended , Just a demonstration !

Be careful python Identifiers cannot contain special characters , Such as ~、@、!、#、$ wait .

3.python Reserved words

Reserved words are keywords , We can't use them as any identifier names .Python The standard library provides a keyword module , We can use it to view all reserved words in the current version :

>>> import keyword
>>> keyword.kwlist
['False', 'None', 'True', '__peg_parser__', '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']

There is no need to memorize the keywords here , There is no need to know the full meaning , Because when you use keywords as identifiers, you will be prompted directly for syntax errors ,

>>> and = 1
File "<input>", line 1
and =1
^
SyntaxError: invalid syntax

4. notes

Annotating code is always a good habit !

python There is only one comment , namely :

# The first note 
# I'm a one-way note 

This comment can only be single line , But there are other ways to keep the code from running . namely :

""" This is a multiline comment This is a multiline comment """
''' You can also comment multiple lines with three single quotes '''

actually (""") and (’’’) All represent multi line strings , Here the code becomes a string , Naturally, it will not work !

If you use multiline comments under classes and functions , For example, the following :

def func(a, b):
""" This is the function documentation . :param a: Addition number :param b: Addition number :return: and """
return a + b
class Foo:
""" This class initializes a age Variable """
def __init__(self, age):
self.age = age

This annotation has a special purpose , Used to __doc__ Provide document content , These contents can be through off the shelf tools , Automatically collect , Form help documents . But the position of this annotation is fixed , As shown above .

in addition , stay linux In the environment , You can use the following comments to determine Python The path of the interpreter :

#!/usr/bin/env python
# Use... In the system environment variable python
#!/usr/bin/python3
# Use a fixed version of python
.....

This line is annotated on the first line , And it's only useful by directly accessing files , Such as :

$ ./xxxx.py

5. Code indentation

Python The most distinctive feature is the use of indentation to represent code blocks . The number of indented spaces is variable , however Statements in the same code block must contain the same number of indented spaces .

sentence : In the code , Be able to express a meaning completely 、 The shortest code for operation or logic , It's called a statement .

Python Standard statements do not require semicolons or commas to indicate the end of the statement , Simply changing the line means that the statement has ended , The next sentence begins .

# This is a class code block 
class Func:
# This is the code block of a function in the class 
def __init__(self, x, y):
self.x = x
self.y = y
def get_x(self):
return self.x

A code block is a set of statements linked together to accomplish a particular function . There is judgment 、 loop 、 function 、 Classes and other code blocks .

If the number of spaces indented in the code block is inconsistent , May trigger IndentationError: unexpected indent abnormal .

Here we need to pay attention to tab and space Transformation , Now mature compilers will automatically tab Convert to four spaces !

6. Multi line statement

Use backslash (\),

>>> string='i like you,'+\
'you just refuse me!'+\
'i am sad....'
>>> string
'i like you,you just refuse me!i am sad....'

Pay attention to [], {}, or () Multiple lines in , You don't need to use backslashes (\), Directly enter , Then write .

>>> print(' I love you! ,'
+' Like flies love cow dung !')
I love you! , Like flies love cow dung !

7.import and from…import

stay Python use import perhaps from…import To import the corresponding module .

  • The whole module (somemodule) Import , The format is :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 into , The format is :from somemodule import *

import sys
print('================Python import mode==========================')
print (' The command line arguments are :')
for i in sys.argv:
print (i)
print ('\n python Path is ',sys.path)
# perhaps 
from sys import argv,path # Import specific members 
print('================python from import===================================')
print('path:',path) # Because it has been imported path member , So there is no need to add sys.path

8. View help from the command line

python -h

9. matters needing attention

stay linux Pay attention on the platform python The representative probability is 2.7 edition , Please use python3 Instead of

Recommended references :
  • Python3 Basic grammar _w3cschool
  • python Basic grammar - Liu Jiang's python course (liujiangblog.com)
notes : The content of this article is collected and summarized on the Internet , For learning only !

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved