Python Basic Syntax

Source: Internet
Author: User

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 and let you quickly learn Python programming.

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:

$ pythonPython 2.7.6 (Default, Sep 9 2014, 15:04:36) [Gcc4.2.1 compatible apple LLVM Span class= "lit" >6.0  (clang- 600.0. 39] on Darwintype  " Help ", " copyright ", span class= "str" > "credits"  or  "license" Span class= "PLN" > for more Information.>>>               

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

Enter the following text information in the Python prompt, and then press ENTER to see the effect of the operation:

>>>Print"Hello, python!" ;

In Python version 2.7.6, the above example output is as follows:

Hello,Python!  
Script-type programming

Invoking the interpreter from the script parameter begins execution of the script until the script finishes executing. When the script finishes executing, the interpreter is no longer valid.

Let's write a simple Python scripting program. All Python files will be extended with a. py extension. Copy the following source code to the test.py file.

Print"Hello, python!" ;

Here, suppose you have set up the Python interpreter PATH variable. Run the program using the following command:

$ python test.  PY 

Output Result:

Hello,Python!  

Let's try another way to execute a Python script. Modify the test.py file as follows:

#!/usr/bin/pythonPrint"Hello, python!" ;

Here, assuming that your Python interpreter is in the/usr/bin directory, execute the script using the following command:

+x Test.  PY     # script file Add executable permissions ./test.  PY       

Output Result:

Hello,Python!  
Python identifiers

In Python, identifiers are made up 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, which is not directly accessible by the _foo, must be accessed through the interface provided by the class and cannot be imported with the FROM XXX import *;

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

Python can display multiple statements on the same line, separated by semicolons , such as:

>>>print' hello ';  Print' Runoob ';  Hellorunoob      
Python reserved characters

The following list shows the reserved words in Python. These reserved words cannot be used as constants or variables, or as any other identifier name.

All Python keywords contain only lowercase letters.

and Exec Not
Assert Finally Or
Break For Pass
Class From Print
Continue Global Raise
Def If Return
Del Import Try
Elif Inch While
Else Is With
Except Lambda Yield
Line and indent

The biggest difference between learning Python and other languages is that Python's code block does not use curly braces {} 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 indented is variable, but all code block statements must contain the same amount of indentation whitespace, which must be strictly enforced. As shown below:

Iftrue:    print"True"else:print"False"    

The following code will execute the error:

#!/usr/bin/python#-*-coding:utf-8-*-# file name: test.pyifTrue:print"Answer"  Print"True"else:print"Answer"# no strict indentation, error print"False"  on execution 

Executing the above code, the following error alert will appear:

$ python test.  PY    File"test.py",print"False"^indentationerror: not Match any outer indentation             level

Indentationerror:unindent does not match any outer indentation level error indicates that the indentation you use is inconsistent, there are tab indents, some spaces are indented, Change to a consistent.

If this is a indentationerror:unexpected indent error, the Python compiler is telling you "Hi, man, your file is not in the right format, it could be a question of misaligned tabs and spaces", all Python The format requirements are very strict.

Therefore, you must use the same number of indent spaces in a Python code block.

It is recommended that you use a single tab or two spaces or four spaces at each indent level, and remember not to mix

Multi-line statements

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

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

=+         + item_three   

The statement contains [], {}, or () parentheses do not need to use a multiline connector. The following example:

=[' Monday ',' Tuesday ',' Wednesday ',' Thursday ',' Friday '] 
Python Quotes

Python can use quotation marks ( ' ), double quotation marks ( " ), three quotation marks (" ' or "") 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 more than one line, writing a shortcut syntax for multiple lines of text, often used in a document string, 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 starts with #.

#!/usr/bin/python#-*-coding:utf-8-*-# file name: test.py# first comment print"Hello, python!" ; # A second comment      

Output Result:

Hello,Python!  

Annotations can be at the end of a statement or an expression line:

="Madisetti"# This is a comment 

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

#!/usr/bin/python#-*-coding:utf-8-*-# file name: test.py"This is a multiline comment, using single 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. This is a multiline comment, using double quotation marks. """
Python Empty 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. 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.

Wait for user input

The following program executes and waits for user input, and then exits after pressing ENTER:

#!/usr/bin/python#-*-coding:utf-8-*-raw_input("Press ENTER to exit, any other key displays ... \ n")  

In the above code,\ n implements line wrapping. Once the user presses ENTER (enter) key to exit, the other keys are displayed.

Show multiple statements on the same line

Python can use multiple statements in the same row, with semicolons (;) split between statements, and here's a simple example:

#!/usr/bin/pythonimport sys;  =' Runoob '; sys.  StdOut.  Write(+' \ n ')             

Execute the above code and enter the result:

$ python test.  Pyrunoob 
Print output

Print default output is a newline, if you want to implement a non-wrapping need to add a comma at the end of the variable ,

#!/usr/bin/python#-*-coding:utf-8-*-x=  "a" y= "B" # line-wrap output print Xprint< Span class= "PLN" > Yprint  '---------' # does not wrap output print Xprint Y,# no newline output print X,y               

The result of the above instance execution is:

AB---------a b a B 
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).

The following example:

If:    elif: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:

$ python-H usage:Python[Option] ... [-C-CMD| -M MoD|File| -] [Arg] ... Options andArguments(andcorresponding environment variables): -C-CMD:Program passedInch As String (Terminates option list) -D:Debug outputFrom parser  (also pythondebug= x)  -e : Ignore environment variables  (such as Pythonpath)  - h : printthis help message and  Exit [ Etc.              /span>                

When we execute Python as a script, we can receive command-line input parameters, which can be referenced using Python command-line parameters.

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