Six ways to interpret Python's code structure

Source: Internet
Author: User
Tags bitwise operators
This article mainly introduces six aspects of the code structure of the interpretation of Python, small series feel very good, and now share to everyone, but also for everyone to do a reference. Let's take a look at it with a little knitting.

First, comments

Use # or three-quote notation.


Second, the connection

Use a backslash \ connection.

>>> alphabet = ' ABCDEFG ' + \ ...                         ' Hijklmnop ' + \ ...                         ' Qrstuv ' + \ ...                         ' WXYZ '

The line connector is also required if the Python expression takes up a lot of rows.

>>> 1 + 2 + \ ... 36


Third, if, elif and Else

Common operators:

Arithmetic operators:

Comparison operators:

Assignment operators:

Logical operators:

Member operators:

Identity operator:

Bitwise operators:

* Bitwise negation Operation rule (bitwise negation plus 1) detailed http://blog.csdn.net/wenxinwukui234/article/details/42119265

Operator Precedence:

Input () is a string;

Conversion between string and integer ———— int () str ()

Short Circuit principle:

And the first is false when not to judge the back, directly to false;

Or the first one is really not going to judge the second one, directly to true.

Cases that would be considered false:

Boolean

False

Null type

None

Integral type

0

Floating point Type

0.0

Empty string

''

Empty list

[]

Empty tuple

()

Empty dictionary

{}

Empty collection

Set ()



Iv. using while for looping

Examples of using if, elif, and else conditions are top-down, but sometimes we need to repeat some of the operations-loops.

>>> count = 1>>> while Count <= 5:     ... Print (count)     ... Count + = 1...12345

Use break to jump out of a loop

>>> while True: ...     Stuff = input ("String to capitalize [type Q to quit]:")     ... if stuff = = ' Q ': ...             Break ...     Print (Stuff.capitalize ()) ... String to capitalize [type Q to Quit]:testteststring to capitalize [type Q to quit]:d Arren Chendarren chenstring to Capita lize [Type Q to Quit]:q

Use continue to start loop

While True:    value = input (' Integer, please [Q-quit]: ')    if value = = ' Q ': Break number    = Int (value)    I F number% 2 = = 0:        continue    print (number, ' squared is ', number*number)    integers, please [q to Quit]:>? squa Red is 1Integer, please [q to Quit]:>? 2Integer, please [q to Quit]:>? Squared is 9Integer, please [q to Quit]:>? Squared is 25Integer, please [q to Quit]:>? 6Integer, please [q to Quit]:>? Q

Out-of-loop use else:

When the while loop ends normally (without using break jumps), the program goes to the optional else segment.

Numbers = [1,3,5]position = 0while position < len (numbers): number    = numbers[position]    If number% 2 = = 0:        Print (' Found even number ', number)        break    position + = 1else:    print (' No even number Found ') ... No even number found



V. Using a for iteration

Tables, strings, tuples, dictionaries, collections, and so on are all objects that can be iterated in Python. A tuple or list produces one item during an iteration, and a string iteration produces a character.

Word = ' Darren Chen ' for I in Word:    print (i)    Darrenchen

Iterating over a dictionary (or key () function of a dictionary) returns the keys in the dictionary

Home = {"Man": ' Chenda ', ' Woman ': ' Lvpeipei '}for i in Home:    print (i)    Manwoman

To iterate over a value, you can use the values () of the dictionary

>>> for value in accusation. VALUES (): ...         Print (value)     ... Ballroom Lead Pipe

As with while, you can use break to jump out of the loop and use continue to start the loop.

Out-of-loop use else:

>>> cheeses = [] >>> for cheese in cheeses: ...             Print (' This shop has some lovely ', cheese)             ... Break ...      else: # No break means no cheese              found ... Print (' This isn't much of a cheese shop, is it? ') ... This isn't much of a cheese, is it?

Use Zip () to iterate through multiple sequences in parallel:

>>> days = [' Monday ', ' Tuesday ', ' Wednesday '] >>> fruits = [' banana ', ' orange ', ' peach '] >>> Dr  inks = [' coffee ', ' tea ', ' beer '] >>> desserts = [' tiramisu ', ' ice cream ', ' pie ', ' pudding '] >>> for day, Fruit, drink, dessert in zip (days, fruits, drinks, desserts):         ... Print (Day, ": Drink", drink, "-eat", fruit, "-enjoy", dessert) ... Monday:drink coffee-eat Banana-enjoy Tiramisu tuesday:drink tea-eat Orange-enjoy ice cream Wednesday:drink B Eer-eat Peach-enjoy Pie

Use the zip () function to pair two tuples. The return value of a function is neither a tuple nor a list, but a consolidated iteration variable:

>>> 中文版 = ' Monday ', ' Tuesday ', ' Wednesday ' >>> French = ' Lundi ', ' Mardi ', ' mercredi ' >>> lis T (Zip (中文版, French)) [(' Monday ', ' Lundi '), (' Tuesday ', ' Mardi '), (' Wednesday ', ' mercredi ')]# With the Dict () function and the return value of the zip () function you can get a miniature dictionary:>>> dict (Zip (English, French)) {' Monday ': ' Lundi ', ' Tuesday ': ' Mardi ', ' Wednesday ': ' mercredi '}

Use range () to generate a sequence of natural numbers

>>> for x in range (0, 3): ...         Print (x) ... 0 1 2>>> list (range (0, 11, 2)) [0, 2, 4, 6, 8, 10]


Six, the derivation of the formula

A derivation is a way to quickly profile a data structure from one or more iterators.

List-derived

>>> number_ list = List (range (1, 6)) >>> number_ list [1, 2, 3, 4, 5]>>> number_ list = [numb Er for number in range (1, 6)] >>> number_ list [1, 2, 3, 4, 5]>>> number_ list = [number-1 for number In range (1, 6)] >>> number_ list [0, 1, 2, 3, 4]>>> a_ list = [number of number in range (1, 6) if Num ber% 2 = = 1] >>> a_ list[1,3,5] #嵌套循环 >>> rows = Range (1, 4) >>> cols = Range (1, 3) >>&G T Cells = [(row, col) for row in rows for col in cols] >>> for cell in cells: ...         Print (cell) ... (1, 1) (1, 2) (2, 1) (2, 2) (3, 1) (3, 2)

Dictionary derivation type

{key_ Expression:value_ expression for expression in iterable}>>> word = ' letters ' >>> letter_ count s = {Letter:word. Count (letter) of the In Set (Word)} >>> letter_ counts {' t ': 2, ' l ': 1, ' E ': 2, ' R ': 1, ' S ': 1}

Set Deduction formula

>>> A_ set = {number for number in range (1, 6) if number% 3 = = 1} >>> A_ set {1, 4}

Generator derivation--the tuple is not derived, in fact, between parentheses is the generator derivation, it returns a generator object.

>>> Number_ thing = (number for number in range (1, 6)) >>> type (Number_ thing) < class ' Generotor ' &G t; #可以直接对生成器对象进行迭代 >>> for number in Number_ thing:             ... Print (number) ... 1 2 3) 4 5

#通过对一个生成器的推导式调用list () function to make it similar to a list-deduction

>>> number_ list = list (Number_ thing) >>> number_ list [1, 2, 3, 4, 5]    a generator can only run one

Times. Lists, collections, strings, and dictionaries are stored in memory, but the generator only produces values in the run and is not saved, so you cannot reuse or back up a generator.

If you want to iterate over this generator again, you'll find it erased:

>>> Try_ again = List (Number_ thing) >>> Try_ again []
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.