Python Learning Diary (fourth week)

Source: Internet
Author: User

Set Data type

Start with a line of code to illustrate

# !/usr/bin/env pythons2== {33,12,33,32121} for in s:      print (i)print(type (s))print(type (s2)) S1=Set () S1.add (one) s1.add (s1.add)print(S1)

The following code runs the result

32121  A  - ' Set ' ' Dict '>}

Through the results of the code can be seen

    • Set is a set of elements that is an unordered and non-repeating element
    • Create set set and dictionary {} only through internal elements can you show the difference
    • Creating an empty set collection is best done using the method of Set () and then adding elements through the Add method

Here are some common methods for set sets

classset (object):"""set (), new empty Set object Set (Iterable), new set object Build an unordered collection of UN    Ique elements. """    defAdd (self, *args, **kwargs):#Real Signature Unknown        """the add an element to a set, adding the element this and no effect if the element is already present. """        Pass     defClear (Self, *args, **kwargs):#Real Signature Unknown        """Remove all elements from the this set. Clear Content"""        Pass     defCopy (self, *args, **kwargs):#Real Signature Unknown        """Return A shallow copy of a set. Shallow copy"""        Pass     defDifference (self, *args, **kwargs):#Real Signature Unknown        """Return The difference of both or more sets as a new set.        A is present, and B does not exist (i.e. all elements the is in this set and not the others.) """        Pass     defDifference_update (self, *args, **kwargs):#Real Signature Unknown        """Remove all elements of another set from the this set. Removes the same element from the current collection as in B"""        Pass     defDiscard (self, *args, **kwargs):#Real Signature Unknown        """Remove an element from a set if it is a member. If the element is not a member, does nothing. Removes the specified element, no error is present"""        Pass     defIntersection (self, *args, **kwargs):#Real Signature Unknown        """Return the intersection of sets as a new set. Intersection (i.e. all elements, that is in both sets. )        """        Pass     defIntersection_update (self, *args, **kwargs):#Real Signature Unknown        """Update a set with the intersection of itself and another. The intersection and update to a"""        Pass     defIsdisjoint (self, *args, **kwargs):#Real Signature Unknown        """Return True If the sets has a null intersection. Returns true if there is no intersection, otherwise false"""        Pass     defIssubset (self, *args, **kwargs):#Real Signature Unknown        """Report Whether another set contains the this set. Whether it is a sub-sequence"""        Pass     defIssuperset (self, *args, **kwargs):#Real Signature Unknown        """Report Whether the this set contains another set. is the parent sequence"""        Pass     defPop (self, *args, **kwargs):#Real Signature Unknown        """Remove and return an arbitrary set element. Raises keyerror if the set is empty. remove Element"""        Pass     defRemove (self, *args, **kwargs):#Real Signature Unknown        """Remove an element from a set; it must is a member. If the element is not a member, raise a keyerror. Removes the specified element, no error is present"""        Pass     defSymmetric_difference (self, *args, **kwargs):#Real Signature Unknown        """Return The symmetric difference of both sets as a new set.        Symmetric difference set (i.e. all elements, that is in exactly one of the sets.) """        Pass     defSymmetric_difference_update (self, *args, **kwargs):#Real Signature Unknown        """Update a set with the symmetric difference of itself and another. Symmetric difference set and updated to a"""        Pass     defUnion (self, *args, **kwargs):#Real Signature Unknown        """Return The union of sets as a new set.        The i.e all elements is in either set.) """        Pass     defUpdate (self, *args, **kwargs):#Real Signature Unknown        """update a set with the Union of itself and others. Updates"""        Pass
Ternary operations

Ternary operations (Trinocular operations) are abbreviations for simple conditional statements.

# Writing Format  ifelse   # Assigns a value of 1 to the result variable if the condition is true, otherwise the value 2 is assigned to the result variable
Supplement to conditional judgment

When a conditional 1 or condition 2 and condition 3 is found in the IF Judgment statement

Execute in order when the condition is met, you won't find it.

It is therefore necessary to change (condition 1 or Condition 2) and condition 3 to

Depth copyFirst explain

In the following environments

When a memory address is found, the data content is considered to be found

For numbers and strings

Variable ======== House name

memory address (actual data) ===== House address

Assignment ======== House name-house address

Memory ======== Intermediary (there are many listings)

Shallow copy

Look at the House address list

A shallow copy and a deep copy are meaningless because they always point to the same memory address. (House address)

For dictionaries, Ganso, lists

Dictionaries, Ganso, and lists are the equivalent of houses in houses with many rooms inside

House =[Room, room number, room number]

So the dictionary, the Ganso, the list of the room numbers stored in the house = = = House Room Number Table

For shallow copies

Equivalent to copying a house room number table

For deep copy

House by room number comparison

Attention!! Due to the optimization of strings and numbers within Python , the same address is also pointed at the last floor ( built by the room number of the house)

Can be understood as

Deep copy, recreate all the data in memory (excluding the last layer, i.e., Python's internal optimization of strings and numbers)

Function

The purpose of a function or method is to integrate a large number of repetitive code in the program, making the program more concise and understandable.

Functional programming The most important thing is to enhance the reusability and readability of code

Definition of a function
def function name (parameter):           ...    function Body    ...    return value

The definition of a function is defined by the DEF keyword + function name

The definition of a function has the following main points:
    • def: A keyword that represents a function
    • Function name: the names of functions, which are called later by function name
    • Function Body: A series of logical calculations in a function, such as sending a message, calculating the maximum number in [11,22,38,888,2], etc...
    • Parameters: Providing data for the function body
    • Return value: Once the function has finished executing, it can return data to the caller.

System built-in functions

return value of the function

A function is a function block that executes successfully or is required to inform the caller by the return value.

For example:

# !/usr/bin/env python def   Funcl ():    return" program executed "= funcl () Print (r)

Return value can be a string or other data type

By default, return returns None:

Note: Once you encounter a return, the following code will no longer execute

Parameters of the function

When defining a function, we determine the name and position of the parameter, and the interface definition of the function is completed. For the caller of the function, it is sufficient to know how to pass the correct arguments and what values the function will return, and the complex logic inside the function is encapsulated and the caller does not need to know.

The parameter of the function is to give a data inside the function, so that the internal code can be repeated and can produce different results for reuse


For example, calculate the square number of X

def Power (x):     return x * x
>>> Power (5)25>>> Power (225)

The square number of any number can be obtained by changing the value of X.

There are 3 types of parameters for a function

    • Common parameters such as the x in the example just
    • Default parameters
    • Dynamic parameters
Default parameters

The default parameter gives the parameter a default value.

For example

# !/usr/bin/env python def Power (x):     return x * xpower ()

When the X value is given, the program will give an error.

Traceback (most recent):   " c:/users/zhang/pycharmprojects/untitled/blog.py "  in <module>    'x'

Modify the program

# !/usr/bin/env python def Power (x=0):    return x *=print(Power ())

This allows the program to have a default value even if it is not given an X value. So the program runs normally

Dynamic parameters

The parameters of a function can be not only a variable, but also a list, a dictionary, etc.

def func (*args):    print  args#  execution mode one func (11,33,4,4454,5 #  execution mode two li = [11,2,2,3,3,4,54]func (*li) Dynamic Parameters
defFunc (* *Kwargs):Printargs#execution Mode oneFunc (name='Wupeiqi', age=18)#mode of execution twoLi = {'name':'Wupeiqi', Age:18,'Gender':'male'}func (**li) Dynamic Parameters

Python Learning Diary (fourth week)

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.