Python Syntax Quick Start guide

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.
The first Python program
Interactive Programming
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 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 outputs the following results:

Hello, python!.


If you are running a new version of Python, you will need to use parentheses in the print statement such as:

>>> print ("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:

$ chmod +x test.py   # script file add executable permissions $./test.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.
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.

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:

If true:  print "True" Else:print "False"


The following code will execute the error:

#!/usr/bin/python#-*-coding:utf-8-*-# file name: test.py if True:  print "Answer"  print "True" Else:  print " Answer "  # no strict indentation, keep print" False "on execution

$ python test.py  File "test.py", line 5  if True:  ^indentationerror:unexpected Indent

Indentationerror:unexpected indent error is the Python compiler is telling you "Hi, man, your file is not in the wrong format, it may be the tab and space is not aligned", all Python is very strict format requirements.
If it is indentationerror:unindent does not match any outer indentation level error indicates that you use the Indentation method is inconsistent, there are some tab indentation, some space indentation, to be consistent.
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:

Total = Item_one + \    Item_two + \    item_three

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

days = [' Monday ', ' Tuesday ', ' Wednesday ',    ' Thursday ', ' Friday ']


Python Quotes
Python receives single quotation marks ('), double quotation marks ("), and three quotation marks (" ' "" ") to denote the string, and the beginning of the quotation mark must be the same type as the end.
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 = ' word ' sentence = ' This is a sentence. "paragraph =" "" 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:

Name = "Madisetti" # this is a comment

A multiline comment in Python uses three single quotation marks ("') or three single 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 will wait for user input after hitting enter:

#!/usr/bin/pythonraw_input ("\n\npress the Enter key to exit.")

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, and here's a simple example:

Import SYS; x = ' Foo '; Sys.stdout.write (x + ' \ n ')


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 expression:   suite elif expression:   Suite else:   

Command-line arguments
Many programs can perform some operations to see some basic letters, 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 and arguments (and corresponding environment variables):-C Cmd:program passed in As String (terminates option L IST)   -D: Debug output from parser (also pythondebug=x)-e   : Ignore environment variables (such as PYTHONPATH)-h< c7/>: Print this help message and exit  
  • 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.