Python Basics 2

Source: Internet
Author: User

List

One of the data types built into Python is the list: Lists. A list is an ordered set of elements that can be added and removed at any time. The claim type is not displayed, but as long as this is the type of expression.

classlist=["Han Meimei", "Wangchuang", "Hello"]

classlist=["Han Meimei", "Wangchuang", 123, "Hello"]

classlist=["Han Meimei",["Wangchuang", 123], "Hello"]

The list can be all of the same type, or it can be of different types, and then you can nest lists.  The same elements can exist! distinguish between [] and () Usage scenarios

To classlist=["Han Meimei", ["Wangchuang", 123], "Hello"] For example demonstration additions and deletions

Increase

Classlist.append ("Qaz")--"classlist" into ["Han Meimei", ["Wangchuang", 123], "Hello", "Qaz"] add element at the end Appen D (Element)

Classlist.insert (1,123)--"classlist" to ["Han Meimei", 123,["Wangchuang", 123], "Hello"] add element Insert anywhere ( I, Element)

Delete

Classlist.pop ()-"classlist" becomes ["Han Meimei", ["Wangchuang", 123]] Delete the end element POPs (), will return the popup element and change The elements in the list. Print (A=classlist.pop ())--"Hello"

Classlist.pop (1)--"classlist changed to [" Han Meimei "," Hello "] delete the specified position element pop (i)

Change

classlist[0]= "Cold Plum"-"classlist" into ["Cold Plum", ["Wangchuang", 123], "Hello"] to replace an element with another element, you can directly assign to the corresponding index position

Check

Classlist[0],,,,, Classlist[len (classlist)-1] index subscript starting from 0, with Len (classlist)-1 end of positive sequence Find

Classlist[-1],classlist[-2],,,,,,, Classlist[-len (classlist)] index subscript starting from 1, with Len (classlist) ending in reverse to find the penultimate first, The second one ....

Number of elements

Len (classlist) len (List's name)

Tuple

Another ordered list is called a tuple : a tuple. Tuple and list are very similar, but once the tuple is initialized, it cannot be modified , for example, the name of the classmate is also listed:

>>> classmates = (‘Michael‘, ‘Bob‘, ‘Tracy‘)

Now, classmates this tuple cannot be changed, and it does not have a append (), insert () method. Other methods of acquiring elements are the same as lists, and you can use them normally, classmates[0] classmates[-1] but you cannot assign them to another element. You can define and find only

What is the meaning of immutable tuple? Because the tuple is immutable, the code is more secure. If possible, you can use a tuple instead of a list as much as possible.

The trap of a tuple: when you define a tuple, the elements of a tuple must be determined when defined, such as:

>>> t = (1, 2)>>> t(1, 2)

If you want to define an empty tuple, you can write () :

>>> t = ()>>> t()

However, to define a tuple with only 1 elements, if you define this:

>>> t = (1)>>> t1

The definition is not a tuple, it is 1 this number! This is because the parentheses () can represent both tuple and parentheses in the mathematical equation, which creates ambiguity, so Python rules that, in this case, the parentheses are calculated, and the result is naturally 1 .

Therefore, only 1 elements of a tuple definition must be added with a comma , to disambiguate:

>>> t = (1,)>>> t(1,)

Python will also add a comma when displaying a tuple of only 1 elements, , lest you misunderstand the parentheses in the mathematical sense.

Finally, let's look at a "mutable" tuple:

>>> t = (‘a‘, ‘b‘, [‘A‘, ‘B‘])>>> t[2][0] = ‘X‘>>> t[2][1] = ‘Y‘>>> t(‘a‘, ‘b‘, [‘X‘, ‘Y‘])

This tuple is defined by 3 elements, respectively ‘a‘ , ‘b‘ and a list. Doesn't it mean that once a tuple is defined, it's immutable? Why did you change it later?

Don't worry, let's take a look at the definition when the tuple contains 3 elements:

When we put the list element ‘A‘ and ‘B‘ modify ‘X‘ it to and ‘Y‘ after, the tuple becomes:

On the surface, the elements of a tuple do change, but in fact it is not a tuple element, but a list element. The list that the tuple initially points to is not changed to another list, so theso-called "invariant" of a tuple is that each element of a tuple is directed to never change. That is, pointing ‘a‘ , cannot be changed to point ‘b‘ , point to a list, can not be changed to point to other objects, but the list itself is variable !

After understanding "point to invariant", how do you create a tuple that does not change the content? It is important to ensure that each element of a tuple cannot be changed.

Conditional judgment

If condition:

Statement

Elif Conditions:

Statement

elif conditions:

Statement

Else

Statement

ifStatement execution has a characteristic, it is to judge from the top, if in a certain judgment True , the statement corresponding to the execution of the sentence, will ignore the remaining elif andelse。

ifThe judging conditions can also be abbreviated, such as writing:

if x:    print(‘True‘)

As long as a non- x 0 value, a non-empty string, a non-empty list, etc., it is judged True , otherwise False .

This is because the input() returned data type is str str not directly compared to an integer and must first be str converted to an integer. Python provides a int() function to do this thing:

s = input(‘birth: ‘)birth = int(s)if birth < 2000:    print(‘00前‘)else: print(‘00后‘)

Run again to get the right results. But what if I enter abc it? And you get an error message:

call last):  File "<stdin>", line 1, in <module>ValueError: invalid literal for int() with base 10: ‘abc‘

The original int() function found a string is not a valid number when the error occurs, the program exits.

Python Basics 2

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.