Python Basic--python3 Basic syntax

Source: Internet
Author: User
Tags iterable natural string

Python3 Basic Syntax

Coding

By default, Python3 source files are encoded in UTF-8, and all strings are Unicode strings. Of course, you can also specify a different encoding for the source file, for example:

#-*-coding:cp-1252-*-


Identifier

1. The first character must be a letter or an underscore in the alphabet;

2. The other parts of the identifier are composed of letters, numbers, and underscores;

3. Identifiers are case sensitive.

Note: In Python3, non-ASCII identifiers are also allowed.


Python reserved word

Reserved words are keywords, and we cannot use them as any identifier names. Python's standard library provides a keyword module that can output all the keywords for the current version:

>>> import keyword>>> keyword.kwlist[' False ', ' None ', ' True ', ' and ', ' as ', ' assert ', ' Break ', ' class ', ' Continue ', ' Def ', ' del ', ' elif ', ' Else ', ' except ', ' finally ', ' for ', ' from ', ' global ', ' if ', ' import ', '-', ' is ', ' LAMBD A ', ' nonlocal ', ' not ', ' or ', ' Pass ', ' raise ', ' return ', ' Try ', ' when ', ' with ', ' yield ']


Comments

The single-line comment in Python begins with #, for example:

#!/usr/bin/python3# First comment print ("hello,python!") #第二个注释

Execute the above code and the output is:

hello,python!

Multiline comments can be made with multiple # numbers:

#!/usr/bin/python3# First comment # second comment print ("hello,python!")

Execute the above code and the output is:

hello,python!


Line and indent

Python's most distinctive feature is the use of indentation to represent blocks of code, without the need to use curly braces {}.

The number of spaces made is mutable, but the statement of the same code block must contain the same number of indentation spaces.

For example:

If True:print ("True") else:print ("False")


The following code does not match the number of spaces in the last line of the statement, resulting in a run error:

If True:print ("Answer") print ("True") else:print ("Answer") print ("False") #缩进不一致, resulting in a run error


The above program is not consistent due to indentation, after execution will appear similar to the following error:

File "c:/users/wuli/pycharmprojects/test.py", line print ("False") #缩进不一致, resulting in a run error ^indentationerror:unindent does not match no outer indentation level


Multi-line statements

Python is usually a line to complete a statement, but if the statement is long, we can use a backslash (\) to implement a multiline statement, for example:

Total = ' Item_one + item_two + item_three '


In [],{}, or (), the multiline statement does not need to use a backslash (\), for example:

Total = [' Item_one ', ' item_two ', ' item_three ', ' item_four ', ' item_five ']


Data type

There are four types of Python: integers, long integers, floating-point numbers, and complex numbers.

1. Integers, such as 1

2. Long integers, larger integers

3. Floating-point numbers, such as 1.23, 3E-2

4. Plural, e.g. 1+2j, 1.1+2.2j


String

Single and double quotes in 1.Python are identical;

2. Use three quotation marks ("' or" ") to specify a multiline string;

3. Escape character ' \ '

4. Natural string, by adding R or R before the string. For example: R "This was a line with \ n" will be displayed, not newline;

5.python allows processing of Unicode strings, prefixed with u or U, for example: U "This is a Unicode string"

6. The string is immutable.

7. The literal cascading string, for example: "This" "is" "string" will be automatically converted to this is string

Word = ' string '

Sentence = "This is a sentence"

Paragraph = "" "This is a paragraph,

can have multiple lines consisting of "" "


Blank Line

A blank line separates between functions or methods of a class, representing the beginning of a new piece of code. The class and function entries are also separated by a line of blank lines to highlight the beginning of the function entry.

Blank lines are different from code indentation, and empty lines are not part of the Python syntax. When you write without inserting a blank line, the Python interpreter runs without errors. But the purpose of a blank line is to separate the code of two different functions or meanings, so that code can be maintained or reconstructed later.

Remember: Blank lines are also part of your program code.


Wait for user input

Executing the following program will wait for user input after pressing ENTER:

#!/usr/bin/python3input ("\ n \ nthe exit after pressing the ENTER key.) ")


In the above code, "\ n" will output two new blank lines before the result output. Once the user presses the key, the program exits.


Show multiple statements on the same line

Python can use multiple statements in the same row, with semicolons (;) split between statements, as in the following example:

#!/usr/bin/python3import SYS; x = ' Python '; sys.stdout.write (x + ' \ n ')


Execute the above code and the result output is:

Python


Multiple statements form a code group

Indenting the same set of statements constitutes a block of code, which we call the code group.

Compound statements such as if, while, Def, and class, the first line begins with a keyword, ends with a colon (:), and one or more lines of code after that line form the code group.

We refer to the first line and the following code group as a clause (clause).

For example:

If Expression:suiteelif expression:suiteelse:suite


Print output

The print default output is newline, and if you want to implement no newline, add end= "" to the end of the variable:

x = ' a ' y = ' B ' #换行输出print (x) print (y) print ('------') #不换行输出print (x,end= "") Print (y,end= "") print ()


The above results are:

AB------a B


Import and From...import

Import the appropriate modules in Python using Import or Form...import.

Import the entire module (somemodule) in the format: import somemodule

Import a function from a module in the format: from Somemodule import somefunction

Import multiple functions from a module in the format: from Somemodule import Firstfunc,secondfunc,thirdfunc

Import all functions in a module in the format: from somemodule import *


Importing the SYS module

Import sysprint (' ================python import mode========================== ');p rint (' command line arguments: ') for I in SYS.ARGV:PR int (i) print (' \ n python path is ', Sys.path)


The output is:

================python Import mode========================== command line arguments are: c:/users/wuli/pycharmprojects/ The project20170523-python3/day1/test1.py python path is [' c:\\users\\wuli\\pycharmprojects\\project20170523-python3\\ Day1 ', ' c:\\users\\wuli\\pycharmprojects\\project20170523-python3 ', ' c:\\users\\wuli\\appdata\\local\\programs\\ Python\\python36\\python36.zip ', ' c:\\users\\wuli\\appdata\\local\\programs\\python\\python36\\dlls ', ' C:\\Users \\wuli\\AppData\\Local\\Programs\\Python\\Python36\\lib ', ' c:\\users\\wuli\\appdata\\local\\programs\\python\\ Python36 ', ' c:\\users\\wuli\\appdata\\local\\programs\\python\\python36\\lib\\site-packages ']


Importing the Argv,path member of the SYS module

From sys import Argv,path # import specific member print (' ================python from import=================================== ') Print (' path: ', path) # because the path member has already been imported, there is no need to add sys.path when referencing it here


The output is:

================python from Import===================================path: [' c:\\users\\wuli\\pycharmprojects\\ Project20170523-python3\\day1 ', ' c:\\users\\wuli\\pycharmprojects\\project20170523-python3 ', ' C:\\Users\\wuli\\ Appdata\\local\\programs\\python\\python36\\python36.zip ', ' c:\\users\\wuli\\appdata\\local\\programs\\python\\ Python36\\dlls ', ' c:\\users\\wuli\\appdata\\local\\programs\\python\\python36\\lib ', ' C:\\Users\\wuli\\AppData\\ Local\\programs\\python\\python36 ', ' c:\\users\\wuli\\appdata\\local\\programs\\python\\python36\\lib\\ Site-packages ']



Command-line arguments

Many programs can perform some operations to see some basic information, and Python can use the-H parameter to view the Help information for each parameter:

C:\users\wuli>python3 -husage: python3 [option] ... [-c cmd | -m  MOD | FILE | -] [ARG]&NBSP, ..... options and arguments  (and corresponding environment variables):-b      : issue warnings about str (bytes_instance),  str (bytearray_instance)          and comparing bytes/bytearray with  str.  (-bb: issue errors)-b     : don ' T write .py[co]  files on import; also PYTHONDONTWRITEBYTECODE=x-c cmd : program  passed in as string  (Terminates option list)-d     :  debug output from parser; also pythondebug=x-e     :  ignore PYTHON* environment variables  (such  as pythonpath)-h     : print this help message and  exit  (ALSO --HELP) [etc.]


Precautions:

1. You can not write the first line of comments under Windows:

#!/usr/bin/python3

The first line of comments is marked with a path to Python that tells the operating system to execute the script, invoking the Python interpreter under/usr/bin.

In addition, there are the following forms (recommended notation):

#!/usr/bin/env Python3

This usage first looks up the Python installation path in the env (environment variable) setting, and then calls the interpreter program under the corresponding path to complete the operation.


2. For comments, you can also use the format "" to write longer notes between the three quotation marks;

"" can also be used to make a description of the function at the header of the function:

def example (anything): ' parameter is an object of any type, and this example function returns it as IS. "' Return anything


3. Help () function

Call the Python Help () function to print a document string that outputs a function:

# See the list of parameters for max built-in functions and the documentation for the specification as follows

>>> Help (max) to built-in function Max in Module Builtins:max (...) Max (iterable, *[, Default=obj, Key=func]), Value Max (Arg1, arg2, *args, *[, Key=func]), value with a Singl E iterable argument, return its biggest item.    The default keyword-only argument specifies an object to return if the provided iterable is empty. With and or more arguments, return the largest argument.


Press: Q Two keys to exit the description document (Linux exit Mode)

If you want only the document string:

>>> print (max.__doc__) #注意, before and after Doc is two underscore Max (iterable, *[, Default=obj, Key=func]), Valuemax (Arg1, Arg2, *args, *[, Key=func]), valuewith a single iterable argument, return to its biggest item. Thedefault keyword-only argument specifies an object to return Ifthe provided iterable is empty. With and or more arguments, return the largest argument.


This article is from the "Wuli_blog" blog, make sure to keep this source http://wuli03960405.blog.51cto.com/1470785/1930651

Python Basic--python3 Basic syntax

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.