Python entry notes (5)

#!/usr/bin/python

print "Hello, World!";

 

 

-d show debug info while parsing

-O Generate optimized code ( .pyo file )

-S starts without introducing where to look for Python paths

-V output Python version number

-X Built-in exceptions (only for strings) have been deprecated since version 1.6.

-c cmd Executes a Python script and returns the result as a cmd string.

file executes the python script in the given python file.

 

 

# -*- coding: UTF-8 -*- or #coding=utf-8 python 3.* version does not need to declare

 

Python identifier

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

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

Identifiers in Python are case-sensitive.

Identifiers that start with an underscore have special meaning. Starting with a single underscore _foo represents a class attribute that cannot be directly accessed, and needs to be accessed through the interface provided by the class, and cannot be imported with from xxx import *;

__foo starting with a double underscore represents a private member of the class; __foo__ starting and ending with a double underscore represents the identifier for special methods in Python, such as __init__() represents the class constructor.

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

>>> print 'hello';print 'world';

hello

world

 

Python reserved characters

andexecnot

assertfinallyor

breakforpass

classfromprint

continueglobalraise

defifreturn

delimporttry

elifinwhile

elseiswith

exceptlambdayield

 

 

 

In Python statements, a new line is generally used as the terminator of the statement.

But we can use a slash ( \ ) to split a line of statements into multiple lines, like this:

total = item_one + \

        item_two + \

        item_three

 

 

 

Statements that contain [], {} or () brackets do not require the use of multiline connectors. The following example:

days = ['Monday', 'Tuesday', 'Wednesday',

        'Thursday', 'Friday']

 

 

Python can use quotation marks ( ' ), double quotation marks ( " ), triple quotation marks ( ''' or """ ) to denote strings, and quotation marks must start and end of the same type.

Among them, triple quotes can be composed of multiple lines, a shortcut syntax for writing multi-line text, often used in docstrings, and in specific places in the file, as comments.

word = 'word'

sentence = "This is a sentence."

paragraph = """This is a paragraph.

Contains multiple statements """

 

 

Python comments

Single-line comments in python begin with #.

#!/usr/bin/python

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

# File name: test.py

 

# first comment

print "Hello, Python!"; # Second comment

Use three single quotes (''') or three double quotes (""") for multi-line comments in python.

#!/usr/bin/python

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

# File name: test.py

 

 

'''

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

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

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

'''

 

"""

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

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

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

"""

 

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

#!/usr/bin/python

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

 

x="a"

y="b"

# newline output

print x

print and

 

print '---------'

# output without wrapping

print x,

print and,

 

# output without wrapping

print x,y

 

 

if expression : 

   suite 

elif expression :  

   suite  

else :  

   suite 

   

   

 

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

 

#!/usr/bin/python

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

import sys

print sys.argv

sys.argv is used to get command line arguments

 

Run the command and execute the result:

./test.py hello

['./test.py', 'hello']

sys.argv[0] represents the path of the file itself, with parameters starting from sys.argv[1].

 

 

 

The first line of the scripting language is to point out what executable program you want the code in your file to use to run it, it's that simple.

#!/usr/bin/python : It tells the operating system to call the python interpreter under /usr/bin when executing the script;

#!/usr/bin/env python (recommended): This usage is to prevent operating system users from not having python installed in the default /usr/bin path. When the system sees this line, it will first look for the python installation path in the env settings, and then call the interpreter program under the corresponding path to complete the operation.

#!/usr/bin/python is equivalent to writing the python path;

#!/usr/bin/env python will go to the environment settings to find the python directory, this is recommended

 

 

multiple variable assignments

Python allows you to assign values ​​to multiple variables at the same time. E.g:

a = b = c = 1

The above example creates an integer object with a value of 1, and the three variables are allocated to the same memory space.

You can also specify multiple variables for multiple objects. E.g:

a, b, c = 1, 2, "john"

In the above example, the two integer objects 1 and 2 are assigned to variables a and b, and the string object "john" is assigned to variable c.

 

 

Python numbers

Numeric data types are used to store numeric values.

They are immutable data types, which means that changing the numeric data type will allocate a new object.

Number objects are created when you specify a value:

var1 = 1

var2 = 10

You can also delete references to some objects using the del statement.

The syntax of the del statement is:

del var1[,var2[,var3[....,varN]]]]]

You can delete references to single or multiple objects by using the del statement. E.g:

part was

del var_a, var_b

Python supports four different numeric types:

int (signed integer)

long (long integer [can also represent octal and hexadecimal])

float

complex (plural)

 

 

Instances of some numeric types:

intlongfloatcomplex

1051924361L0.03.14j

100-0x19323L15.2045.j

-7860122L-21.99.322e-36j

0800xDEFABCECBDAECBFBAEl32.3e+18.876j

-0490535633629843L-90.-.6545+0J

-0x260-052318172735L-32.54e1003e+26J

0x69-4721885298529L70.2E-124.53e-7j

A lowercase l can also be used for long integers, but it is recommended that you use an uppercase L to avoid confusion with the number 1. Python uses L to display long integers.

Python also supports complex numbers. A complex number consists of a real part and an imaginary part, which can be represented by a + bj, or complex(a,b). The real part a and the imaginary part b of the complex number are both floating-point types.

 

 

 

 

Django template tags

if/else tags

The basic syntax format is as follows:

{% if condition %}

     ... display

{% endif %}

or:

{% if condition1 %}

   ... display 1

{% elif condition2 %}

   ... display 2

{% else %}

   ... display 3

{% endif %}

Determine whether to output according to the conditions. if/else supports nesting.

The {% if %} tag accepts and , or or not keywords to judge multiple variables, or to negate variables ( not ), for example:

{% if athlete_list and coach_list %}

     Both athletes and coaches variables are available.

{% endif %}

for tag

{% for %} allows us to iterate over a sequence.

Similar to the case of Python's for statement, the loop syntax is for X in Y , where Y is the sequence to iterate and X is the variable name used in each particular loop.

Each time through the loop, the template system renders everything between {% for %} and {% endfor %}.

For example, given an athlete_list variable with a list of athletes, we can use the following code to display the list:

<ul>

{% for athlete in athlete_list %}

    <li>{{ athlete.name }}</li>

{% endfor %}

</ul>

Adding a reversed to the label causes the list to be iterated in reverse:

{% for athlete in athlete_list reversed %}

...

{% endfor %}

{% for %} tags can be nested:

{% for athlete in athlete_list %}

    <h1>{{ athlete.name }}</h1>

    <ul>

    {% for sport in athlete.sports_played %}

        <li>{{ sport }}</li>

    {% endfor %}

    </ul>

{% endfor %}

ifequal/ifnotequal tags

The {% ifequal %} tag compares two values, and when they are equal, displays all values ​​between {% ifequal %} and {% endifequal %}.

The following example compares two template variables user and currentuser:

{% ifequal user currentuser %}

    <h1>Welcome!</h1>

{% endifequal%}

Like {% if %}, {% ifequal %} supports optional {% else%} tags: 8

{% ifequal section 'sitenews' %}

    <h1>Site News</h1>

{% else %}

    <h1>No News Here</h1>

{% endifequal%}

Annotation label

Django comments use {# #}.

{# This is a comment#}

filter

Template filters can modify the variable before it is displayed. The filter uses the pipe character as follows:

{{ name|lower }}

After the {{ name }} variable is processed by the filter lower, the document uppercase converts the text to lowercase.

Filter pipes can be *socketed*, that is, the output of one filter pipe can be used as the input of the next pipe:

{{ my_list|first|upper }}

The above example takes the first element and converts it to uppercase.

Some filters have parameters. Filter arguments follow a colon and are always enclosed in double quotes. E.g:

{{ bio|truncatewords:"30" }}

This will display the first 30 words of the variable bio.

Other filters:

addslashes : adds backslashes before any backslashes, single or double quotes.

date : format a date or datetime object according to the specified format string parameter, example:

{{ pub_date|date:"F j, Y" }}

length : Returns the length of the variable.

include tag

The {% include %} tag allows the content of other templates to be included in the template.

The following examples all include the nav.html template:

{% include "nav.html" %}

template inheritance

Templates can be reused by inheritance.

Next, we first create the base.html file in the templates directory of the previous project. The code is as follows:

HelloWorld/templates/base.html file code:

<!DOCTYPE html>

<html>

<head>

<meta charset="utf-8">

<title></title>

</head>

<body>

    <h1>Hello World!</h1>

    <p>Test. </p>

    {% block mainbody %}

       <p>original</p>

    {% endblock %}

</body>

</html>

In the above code, the block tag named mainbody is the part that can be replaced by inheritors.

All {% block %} tags tell the template engine that child templates can override these parts.

hello.html inherits base.html and replaces specific blocks. The modified code of hello.html is as follows:

HelloWorld/templates/hello.html file code:

{% extends "base.html" %}

 

{% block mainbody %}<p>Inherited from base.html file</p>

{% endblock %}

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326043080&siteId=291194637