Python Learning notes (ii)

Source: Internet
Author: User
Tags case statement

1 The type and memory of objects in the Python language are determined at run time. When you create an assignment, the interpreter determines the type of the new object based on the syntax and the operands to the right.


2 GAE English is all called Google App Engine. It is a platform for development and hosting of WEB applications in the Google managed data center and currently supports Python, Java, and PHP development

3.httperror:http Error 403:forbidden

Import sys,urllib2req = Urllib2. Request ("Http://blog.csdn.net/nevasun") fd = Urllib2.urlopen (req) while True:    data = Fa.read (1024x768)    if not Len ( Data): Break    sys.stdout.write (data)



This is due to Web site Prohibition Crawler, can be in the request to add header information, disguised as browser access. Add and modify. This crawl down the page is garbled, the site is UTF-8 encoded, need to convert the cost of the system encoding format, so to change two places:

Import sys,urllib2headers = {' user-agent ': ' mozilla/5.0 (Windows; U Windows NT 6.1; En-us; rv:1.9.1.6) gecko/20091201 firefox/3.5.6 '}  req = Urllib2. Request ("Http://blog.csdn.net/lotluck", headers=headers) content = Urllib2.urlopen (req). Read ()    # # UTF-8  Type = Sys.getfilesystemencoding ()    # Local encode format  print content.decode (' UTF-8 '). Encode (type)    # Convert encode format  


4 HTTPS differs from HTTP
HTTPS (Secure hypertext Transfer Protocol): Secure Hypertext Transfer Protocol, HTTP-based, using Secure Sockets Layer (SSL) as a sub-layer of HTTP applications, HTTPS using 443 ports, SSL using 40 bit keyword as RC4 stream encryption algorithm, HTTPS and SSL support use of the digital authentication of the first.
HTTP is the HTTP protocol that runs on top of TCP. All transmitted content is plaintext, and neither the client nor the server can verify the identity of the other.
HTTPS is HTTP running over SSL/TLS, and SSL/TLS is running over TCP. All transmitted content is encrypted and encrypted with symmetric encryption, but the symmetric encryption key is asymmetric encrypted with the server-side certificate. Additionally, the client can verify the server-side identity, and if client authentication is configured, the server side

You can also verify the identity of the client.
1.HTTPS protocol requires a certificate to the CA, General free certificate is very small, need to pay
2.http is a Hypertext Transfer Protocol, the information is plaintext transmission, HTTPS is a secure SSL encryption Transfer Protocol
3.http and HTTPS use a completely different way of connecting the port is not the same, the former is 80, the latter is 443
The 4.http connection is simple and stateless.
The 5.HTTPS protocol is a network protocol built by the SSL+HTTP protocol to encrypt transmission and authentication, which is more secure than the HTTP protocol.


5. Iterators (iterator), sometimes called cursor iterators, are objects that have a next () method , rather than being counted by an index. When you or a loop mechanism (such as a for statement) needs the next item, the next () method that invokes the iterator can get it. When the entry is fully removed, it causes

An stopiteration exception, which is not an indication of an error occurring, just tells the external caller that the iteration is complete. You can use the ITER () function to create an iterator, and another is to customize the class.
>>> a = [122,221,333]
>>> B = iter (a)
>>> B.next ()
122
>>> B.next ()
221
>>> B.next ()
333
>>> B.next ()

Traceback (most recent):
File "<pyshell#6>", line 1, in <module>
B.next ()
Stopiteration
>>>


>>> LST = range (2)
>>> it = iter (LST)
>>> it
<listiterator Object at 0x0000000002c5ebe0>
>>> It.next ()
0
>>> It.next ()
1


6. Variable Exchange
>>> x = 6
>>> y = 5
>>> x, y = y,x
>>> x
5
>>> y
6


7.if...elif...else statements

Example:

# if Elif Else statement

Score = Raw_input ("Score:")

Score=int (Score)

if (score >=) and (Score <= 100):

Print "A"

Elif (Score >=) and (Score < 90):

Print "B"

Elif (Score >=) and (Score < 80):

Print "C"

Else

Print "D"

8. Implementing the switch statement function
Python does not provide a switch statement, and Python can implement the switch statement functionality through a dictionary. The implementation method is divided into two steps. First, define a dictionary. A dictionary is a collection of key-value pairs. Second, the Get () of the calling dictionary gets the corresponding expression.

From __future__ Import Division

x = 1

y = 2

operator = "/"

result = {

"+": X + y,

"-": X-y,

"*": X * y,

"/": X/Y

}

Print Result.get (operator)


9. Another scenario for using the switch branching statement is to create a switch class that processes the program.

A) Create a switch class that inherits from the ancestor class object of Python. Calling the constructor init () initializes the string that needs to be matched and needs to define two member variables, value and fall. Value is used to hold the string that needs to be matched, fall is used to record whether the match was successful, and the initial value is False

, the identity match is unsuccessful. If the match succeeds, the program executes backwards.

b) define a match () method that is used to match the case clause. There are three things to consider here: first, the match succeeds, followed by the default case clause that matches the failure, and finally, when the break is not used in the cases clause.

c) override the __iter__ () method to define the method so that the switch class is used in the loop statement. __ITER__ () calls the match () method for matching. Preserves the word by yield so that the function can iterate through the loop. Also, call the Stopiteration exception interrupt loop.

d) write the calling code in for...in ... Use the switch class in the loop.

Example:

Class switch (object):

def __init__ (self, value): # initializes the value that needs to be matched

Self.value = value

Self.fall = False # Fall is true if there is no break in the case statement that is matched to.

def __iter__ (self):

Yield Self.match # Call the match method to return a generator

Raise Stopiteration # Stopiteration exception to determine if the for loop is over

def match (self, *args): # Method of simulating case clauses

If Self.fall or not args: # If Fall is true, continue to execute the following case clause

# or the case clause has no match, it flows to the default branch.

Return True

Elif Self.value in args: # match success

Self.fall = True

Return True

Else: # match failed

Return False

operator = "+"

x = 1

y = 2

For box in Switch (operator): # switch can only be used in a for in loop

If case (' + '):

Print x + y

Break

If case ('-'):

Print X-y

Break

If case (' * '):

Print x * y

Break

If case ('/'):

Print x/y

Break

If Case (): # Default Branch

Print ""


10 Connection of strings
>>> NFC = [' 11111111 ', ' 22222222222 ']
>>> AFC = [' 33333333 ', ' 44444444444 ']
>>> Print NFC + AFC
[' 11111111 ', ' 22222222222 ', ' 33333333 ', ' 44444444444 ']
>>> Print str (1) + "Dushuai"
1dushuai
>>> print ' 1 ' + "Dushuai"
1dushuai
>>> print 1, ' Dushuai '
1 Dushuai
>>>

11 Numerical comparison
>>> x = 2
>>> if 3 > x > 1:
Print X


2
>>> if 1 < x > 0:
Print X


2

12 traversing two lists at a time
>>> NFC = [' 111 ', ' 222 ']
>>> AFC = [' 333 ', ' 444 ']
>>> for t1,t2 in Zip (NFC,AFC):
Print T1 + "vs." + T2


111vs.333
222vs.444
>>>


13 times the Calendar list to get the serial number and content

>>> Tong = [' Zhao ', ' Tong ', ' Tong ', ' du ', ' Shuai ', ' love ', ' You ']
>>> for index, team in Enumerate (Tong):
Print Index,team


0 Zhao
1 Tong
2 Tong
3 du
4 Shuai
5 Love
6 You
>>>

. Idle integrated development environment built-in function becomes BIF (built-in function) enter PR or other under >>> prompt, press TAB to make a set of suggestions


the variable identifier in 15.python does not have a type, and Python creates a list of data that is like an array-like data structure that is stored in a top-down, numbered 0,1,2,3 ... , the German data in the list can be accessed like an array
movie=["Wo", "Hen", "ni"]
Print Movie[1]
In a simple sentence, the list is an array of hormones that can mix data types


Len (movie) measure length, use for to handle lists of any length, list does not support out-of-bounds checking
The for Each_item in Movie:for Loop is responsible for starting from the list start position
Print Each_item

coun=0;
While Count < Len (movie):
Print (Movie[count])
Count=count+1

17. The list can be nested
Movie = ["The Holy Grail", "The Life of Brain", ["11111", "22222", [44,55,66], "3333"], "the Meaning of Lif"]

For Each_item in Movie:
Print Each_item for loop only prints individual data items for the outer list

The Holy Grail
The Life of Brain
[' 11111 ', ' 22222 ', [44, 55, 66], ' 3333 ']
The meaning of Lif


Two times for Loop
For i in Movie:
If Isinstance (i,list):
For j in I:
Print J
Else
Print I


The Holy Grail
The Life of Brain
11111
22222
[44, 55, 66]
3333
The meaning of Lif


python module where can I use the Code
Import Sys;sys.path


the range () BIF can provide the control you need to iterate over the specified number of times .

For NUM in range (4)
Print num

The 20 module is a text file that contains Python code, and Python has its own namespace end= ' wrap

Python's bif is used to interact with the file, Python's basic input mechanism is based on the line;

Python Learning notes (ii)

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.