Python Learning--python Basic grammar

Source: Internet
Author: User
Tags terminates python script

Interactive programming of the first Python program

Interactive programming does not require the creation of a script file, it is written in the interactive mode of the Python interpreter.

On Linux you only need to enter the Python command at the command line to start interactive programming, prompting the following window:

  

The default interactive programming client is already installed on window when you install Python, and the prompt window is as follows:

  

Enter the text in the Python prompt and press ENTER to see the results of the operation:

Print ' Hello World ';

Output:

Hello World

  

Script-type programming

Let's write a simple Python script, all of the Python scripts with a. py extension, the following is the contents of hello.py:

Print ' Hello python! ';

Run hello.py using the following command:

Python hello.py

Output Result:

Hello python

Python identifiers

In Python, identifiers are composed of letters, numbers, and underscores.

In Python, all identifiers can include English, numeric, and underscore (_), but cannot begin with a number.

Identifiers in Python are case-sensitive.

Identifiers that begin with an underscore are of special significance. A class attribute that begins with a single underscore (_foo) cannot be accessed directly, and is accessed through the interface provided by the class and cannot be imported with "from XXX import *";

A double underscore (__foo) represents a private member of a class; a double underscore (__foo__) represents a special method-specific identifier for Python, such as __init__ (), which represents the constructor of a class.

Line and indent

The biggest difference between learning Python and other languages is that Python's code blocks do not use ({}) to control classes, functions, and other logical judgments. Python's most distinctive feature is the use of indentation to write modules.

The amount of whitespace to indent is variable, but all code block statements must contain the same amount of indentation whitespace, which must be strictly enforced.

Multi-line statements

A new line is generally used as the Terminator for a statement in a Python statement.

But we can use (\) to divide a line of statements into multiple lines, as follows:

Total = Item_one +         +         item_three

The statement contains [],{}, () does not need to use a multiline connector, as follows:

Number = ['one',          'both ',           ' three ']

Python Quotes

Python accepts single quotation marks ('), double quotation marks ("), three quotation marks (" ' "" ") to denote a string, and the beginning and end of the quotation mark must be of the same type.

Where three quotation marks can be composed of multiple lines, writing the shortcut syntax of multiple lines of text, common language file strings, at a specific location of the file, as a comment.

' Word '  " This is a sentence. "" " This is a paragraph.  Contains multiple statements  "" "

  

Python comments

A single-line comment in Python must begin with #.

# First comment Print " Hello python! " # a second comment

Comments can be at the end of a statement or expression line

" Tommy " # This is a comment

A multiline comment in Python uses three single quotation marks ("'), or three double quotation marks (" "").

" " This is a multiline comment, using single quotation marks. This is a multiline comment, using single quotation marks.   "" " this is a multiline comment, using double quotes. This is a multiline comment, using double quotation marks. """

Python space

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. However, the purpose of a blank line is to separate the code of two different functions or meanings, which facilitates the maintenance or refactoring of future code.

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

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).

As follows:

if expression:     elif expression:     Suite  else  :     

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:

Usage:python [option] ... [-C cmd |-M mod | file |-] [arg] ... Options andArguments ( andcorresponding environment variables):-b:don't write. Py[co] files on import; also pythondontwritebytecode=x-C Cmd:program passedinchAs string (terminates option list)-d:debug output fromParser Also pythondebug=x-e:ignore python*environment variables (such as PYTHONPATH)-H:PrintThis Help message andExit (also--Help )-I:inspect interactively after running script; forces a prompt evenifStdIn does notappear to be a terminal; Also pythoninspect=x-m Mod:run Library module as a script (terminates option list)-o:optimize generated bytecode slightly; Also pythonoptimize=x-oo:remove doc-stringsinchaddition to the-O Optimizations-r:use a pseudo-random salt to make hash () values of various types be unpredictable between separate invocations of the INTERP Reter, as a defense against Denial-of-Service Attacks-Q arg:division Options:-qold (Default),-qwarn,-qwarnall,-Qnew-s:don't Add user site Directory to Sys.path; also Pythonnousersite-s:don'T imply'ImportSite'On initialization-t:issue Warnings about inconsistent tab usage (-tt:issue Errors)-u:unbuffered binary stdout andStdErr Also pythonunbuffered=x See mans Page forDetails on internal buffering relating to'- u'-v:verbose (TraceImportstatements); Also pythonverbose=x can be supplied multiple times to increase verbosity-V:PrintThe Python version number andExit (also--version)-W arg:warning control; Arg isAction:message:category:module:lineno also pythonwarnings=Arg-x:skip first line of source, allowing use of Non-unix forms of#!cmd-3:warn about Python 3. x incompatibilities that 2to3 cannot trivially Fixfile:program read fromscript File-: Program Read fromstdin (default; interactive modeifa TTY) arg ...: Arguments passed to programinchSys.argv[1:] Other environment Variables:PYTHONSTARTUP:file executed on interactive startup (no default) PYTHONPATH:';'-separated list of directories prefixed to the default module search path. The result issys.path.PYTHONHOME:alternate<prefix> Directory (or<prefix>;<exec_prefix>). The default module search path uses<prefix>\lib. Pythoncaseok:ignore Caseinch 'Import'statements (Windows). Pythonioencoding:encoding[:errors] Used forstdin/stdout/stderr. Pythonhashseed:ifThis variable isSet to'Random', the effect isThe same as specifying the-R option:a Random value isused to seed the hashes of str, bytes anddatetime objects. It can also is set to an integerinchThe range [0,4294967295] to get hashes values with a predictable seed.

We can receive command-line input parameters when we execute Python in script form.

Python Learning--python Basic grammar

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.