Python Basic Grammar

The Python language has many similarities to languages ​​like Perl, C, and Java. However, there are some differences.

In this chapter we will learn the basic syntax of Python in the future, allowing you to 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 Python commands on the command line to start interactive programming. The prompt window is as follows:

$ python
Python 2.7 .6 (default, Sep 9 2014, 15:04:36)
[GCC 4.2.1 Compatible Apple LLVM 6.0 (clang-600.0.39)]< Span class="pln"> on darwin
Type "help", "copyright", "credits" or< Span class="pln"> "license" for more information.

The interactive programming client is already installed on Window when installing Python. The prompt window is as follows:

Enter the following text message at the python prompt and press Enter to see the results:

>>> print "Hello, Python!"

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

Hello, Python!

Scripting Programming

Invoke the script from the script by calling the interpreter until the script finishes executing. The interpreter is no longer valid when the script is executed.

Let's write a simple Python script. All Python files will have a .py extension. Copy the following source code into the file.

print "Hello, Python !"

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

$ python 

Output results:

Hello, Python!

Let's try another way to execute Python scripts. Modify the file as follows:


print "Hello, Python!"

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

$ chmod +x test .py # Add executable permissions to script files< Span class="pln">
$ ./

Output results:

Hello, Python!

Python identifier

In Python, identifiers consist of letters, numbers, and underscores.

In Python, all identifiers can include English, numbers, and underscores (_), but they cannot begin with a number.

Identifiers in Python are case sensitive.

The identifier at the beginning of the underscore is of special significance. Class attributes that begin with a single underscore _foo that are not directly accessible, need to be accessed through the interface provided by the class, not from xxx import *< /span> and import.

__foo with a double underscore represents a private member of the class, with __foo__ starting with double underscores and ending with Python A special method-specific identifier, such as __init__() represents the constructor of the class.

Python can display multiple statements on the same line by separating them with a semicolon ;, such as:

Python reserved characters

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

All Python keywords contain only lowercase letters.


Lines and indents

Learning The biggest difference between Python and other languages ​​is that Python's code blocks don't use braces {} to control classes, functions, and other logical decisions. The most special feature of Python is to write modules with indentation.

The number of indented blanks is variable, but all code block statements must contain the same number of indented blanks, which must be strictly enforced. As shown below:

if True:
    print "True"
  print "False"

The following code will execute the error:

# -*- coding: UTF-8 -*-
# File name:

if True :
    print "Answer"
    print "True"
    print "Answer"
    # No strict indentation, an error will be reported during execution
  print "False"

Executing the above code will result in the following error alert:

IndentationError: unindent does not match any outer indentation level The error indicates that the indentation methods you use are inconsistent, some are tab indentation, some are indentation, and can be changed to be consistent.

If it is a IndentationError: unexpected indent error, the python compiler is telling you "Hi, dude, the format of your file is incorrect, it may be tab The problem of not being aligned with spaces", all pythons have very strict formatting requirements.

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

It is recommended that you use single tab or two spaces or four spaces at each indentation level, remember not to mix < /p>

Multiple lines

The Python statement generally takes a new line as the terminator of the statement.

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

total = item_one + \
        Item_two + \

statements that contain [], {} or () parentheses do not require the use of multi-line connectors. The following example:

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

Python Quotes

Python can use quotation marks ( ' ), double quotation marks ( " ), triple quotation marks ( ''' or " " ) to represent a string, the same type of quotation marks must be used at the beginning and end.

The three quotation marks can be composed of multiple lines. The quick syntax for writing multiple lines of text is often used for document strings, and is used as a comment at a specific place in the file.

word = 'word'
Sentence = "This is a sentence."< Span class="pln">
Paragraph = """This is a paragraph.
Contains multiple statements """

Python comments

Single line comments in python start with #.

# -*- coding: UTF-8 -*-
# File name:

# first comment
print "Hello, Python!" # second comment

Output results:

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

name = "Madisetti" # This is a comment

Multi-line comments in python use three single quotes (''') or three double quotes (""").

# -*- coding: UTF-8 -*-
# File name:

This is a multi-line comment, using single quotes.
This is a multi-line comment, using single quotes.
This is a multi-line comment, using single quotes.

This is a multi-line comment, using double quotes.
This is a multi-line comment, using double quotes.
This is a multi-line comment, using double quotes.

Python blank line

The function or the method of the class is separated by a blank line, indicating the beginning of a new piece of code. The class and function entries are also separated by a blank line to highlight the beginning of the function entry.

A blank line is different from code indentation. A blank line is not part of the Python syntax. When you write without inserting a blank line, the Python interpreter will not go wrong. But the role of blank lines is to separate two different functions or meanings of code for future maintenance or refactoring.

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

Wait for user input

The following program will wait for user input after execution, and will exit after pressing the Enter key:

# -*- coding: UTF-8 -*-

Raw_input("Press the enter key to exit, any other key displays...\n")

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

Show multiple statements on the same line

Python can use multiple statements on the same line, separated by semicolons (;), the following is a simple example:


import sys; x = 'runoob'; sys.stdout.write(x  + '\n') 

Execute the above code, the input result is:

$ python

Print output

print The default output is a newline. If you want to implement no line breaks, you need to add a comma at the end of the variable ,

The above example execution result is:

a b a b

Multiple statements form a code group

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

Composite statements like if, while, def, and class. The first line begins with a keyword and ends with a colon ( : ). One or more lines of code after the line form a code group.

We refer to the first and subsequent code groups as a clause.

Example below:

if expression :
elif expression :
else :

Command line parameters

Many programs can perform some operations to view some basic information. Python can use the -h parameter to view help information for each parameter:

$ python -h
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 list)
-d : debug output fromparser (also PYTHONDEBUG=x)< Span class="pln">
-E : ignore environment variables (such as PYTHONPATH)
-h : print this help message and exit
[ etc. ] 

welookups is optimized for learning.© welookups .
All Right Reserved and you agree to have read and accepted our term and condition