Basic learning of Python (i)

Source: Internet
Author: User
Tags cos sin

After installing Python and debugging successfully the first Hello Word, the following is the beginning of learning the Python Foundation through the website of Liao Xuefeng. Study site: https://www.liaoxuefeng.com

First, the format of the output

The formatted output is the same as a placeholder in a string, and finally replaces the placeholder with a mutable parameter. The result of the final output; in Python, the format used is the same as the C language, and is implemented by%;

The commonly used placeholders are:

  

Case:

Print (' This is an integer%2d, do you know%02d '% (1, 2)) print (' This is the integer%d, this you know%d '% (1, 2) ') print (' This is the integer%d, this you know%d '% (100, 200))

Output Result:

This is the integer 1, do you know 02 This is the integer 1, this you know 2 this is the integer 100, this you know 200

Analysis: These are formatted output integers,%2d represents the 2-bit output of the pit, so in the output can be seen in the first output is a null, the other%02d represents a two-bit output, with 0 supply occupied, you can get 02 of the output.

Print ('%.2f '% 3.1415926)

Output: 3.14

Analysis: Floating-point numbers retain a two-bit decimal notation

If you are unsure of which format output to use, remember that%s is always working, and it converts any data type to a string.

Print (' Age:%s. Gender:%s '% (+ True))

Output: age:25. Gender:true

Format () is also a formatted output that takes the passed-in parameter in turn, swapping the placeholder {0} {1} {2} in the string ...

Print (' This is a pit: {0}, this is a floating point pit: {1:.1f}%, this is the other pit: {2} '. Format (' I am a pit ', 17.125, 100))

Output: This is a pit: I'm the pit, this is the floating point pit: 17.1%, this is the other pit: 100

Second, use list and tuple 

A List is an ordered set of elements that can be added and removed.

#LIST学习 # Create a listlistinfo = [' aaa ', ' BBB ', ' CCC '];p rint (listinfo) #计算list的长度 len () print (Len (listinfo)) #用索引访问list中的元素p Rint (listinfo[2]) #通过负数倒着取元素print (listinfo[-1]) #list是一个可变的有序表 # append element to list append () listinfo.append (' DDD ') print ( Listinfo) #也可以将插入的元素指定到指定的位置 Insert () Listinfo.insert (2, ' CiCi ') print (listinfo) #删除list末尾的元素 pop (i) I is a variable bit listinfo.pop () print (Listinfo) #把某个元素替换成别的元素listInfo [2] = ' Replace ' print (listinfo) #list的元素类型可以不同 True Case-sensitive setlist = [' AAA ', 111,  True]print (setlist) #list元素也可以是另外一个元素newList = [' java ', ' php ', setlist]print (newlist) # Take the element in the Multidimensional list print (newlist[2][1])

The output results are as follows:

[' AAA ', ' BBB ', ' CCC ']3cccccc[' aaa ', ' BBB ', ' CCC ', ' ddd ' [' AAA ', ' BBB ', ' CiCi ', ' CCC ', ' ddd ' [' AAA ', ' BBB ', ' CiCi ', ' CCC '] [ ' AAA ', ' BBB ', ' replace ', ' CCC ' [' AAA ', 111, true][' java ', ' php ', [' AAA ', 111, true]]111

  tuple Another list is called tuples: tuple. The tuple and list are similar, but the tuple cannot be modified once initialized

The tuple does not have a append () Insert () method because it is immutable. Can only be obtained by keying. Relatively safe relative to list. It is particularly important to note that when using a tuple, the elements of a tuple must be determined.

#tupletupleInfo = (1, 2) print (Tupleinfo)

Output: (1, 2)

#定义一个空的tupletupleInfo = () print (Tupleinfo)

Output: ()

#定义一个只有1个元素的tupletupleInfo = (1111) print (tupleinfo)

Output: 1111

Description: If the following definition is a true tuple, it represents only one element of the tuple

Tupleinfo = (1111,) print (Tupleinfo)

Output: (1111,)

In this case, indirectly through the list to change the tuple actually, the change is a variable list and the tuple does not change, but the indirect is the same as the change.

mylist = [' php ', ' Java ', ' C # ']tupleinfo = (111,222,333, mylist) print (tupleinfo) tupleinfo[3][1] = ' mysql ' Print (tupleinf O)

Output: (111, 222, 333, [' php ', ' Java ', ' C # ']) (111, 222, 333, [' php ', ' MySQL ', ' C # '))

Third, conditional judgment cycle

x = 70;if x <60:    print (' This score is less than 60 ') Elif x >=:    print (' This score is greater than 60 ') Else:    print (' excellent ')

Python needs to be divided into two categories, the first of which is for ... in, the list of the total number of goods tuple data listed, the second is while the way, as long as the conditions of the continuous cycle;

First case:

for item in [' 111 ', ' 222 ', ' 333 ']:    print (item)

Output: 111

222
333

sum = 0n = 99while n > 0:    sum = sum + N    n = n-2print (sum)

Output: 2500

Description: In the loop process can be terminated according to the conditions of the cycle break, can be. Or you can continue to cycle contionue according to the conditions.

Iv. Dist and set

Dist can be interpreted as a map, stored in the form of a key-value pair, with relatively fast query data

Use of #dict and set dictinfo = {' name ': ' CiCi ', ' age ': ' + ', ' sex ': ' Female '}print (dictinfo) print (dictinfo[' name ')

Output: {' name ': ' CiCi ', ' age ': ' + ', ' sex ': ' Female '}

CiCi

Dictinfo = {' name ': ' CiCi ', ' age ': ' + ', ' sex ': ' Female '}print (dictinfo) dictinfo[' name '] = ' dada ' Print (dictinfo)

Output: {' sex ': ' Female ', ' age ': ' + ', ' name ': ' CiCi '}

{' Sex ': ' Female ', ' age ': ' + ', ' name ': ' Dada '}

Description: If locating an element, if the element does not exist, it will be an error;

The #验证key不存在的的方法print (' name ' in dictinfo) print (' Test ' in Dictinfo) print (dictinfo.get (' name ')) print (Dictinfo.get (' Test ') Print (dictinfo.get (' Test ', ' no '))

Output:

True
False
Dada
None
No

The following cases were deleted:

Print (Dictinfo) dictinfo.pop (' name ') print (dictinfo)

Output: {' name ': ' Dada ', ' sex ': ' Female ', ' age ': ' 25 '}

{' Sex ': ' Female ', ' age ': ' 25 '}

Compared with list, Dict has the following features:

    1. The speed of finding and inserting is very fast and will not slow with the increase of key;
    2. It takes a lot of memory, and it wastes a lot of memory.

And the list is the opposite:

    1. The time to find and insert increases as the element increases;
    2. Small footprint and little wasted memory.

Set

The only difference between set and dict is that it does not store the corresponding value, but the set principle is the same as the dict, so it is also not possible to put mutable objects, because it is not possible to determine whether the two Mutable objects are equal, and there is no guarantee that there will be no duplicate elements inside the set.

#set # Initialize Set assignment SetInfo1 = set ([111, 222, 333]) print (SETINFO1) #set没有vlue only key-tangent key cannot be repeated SetInfo2 = set ([111,222,333,3 33,222]) print (SetInfo2) #给set添加元素setInfo2. Add (' 444 ') print (SetInfo2) #删除set元素setInfo2. Remove (' 444 ') print (SetInfo2 )

Output:

{333, 222, 111}
{333, 222, 111}
{' 444 ', 333, 222, 111}
{333, 222, 111}

V. Calling functions

#调用函数print (+) print (ABS ( -100)) print (max (1,2,3,4,5,0,-1,-3)) print (int (' 123 ')) Print (float (' 12.34 ')) print (s TR (12.34)) print (bool (1)) Print (bool ("))

Output:

100
100
5
123
12.34
12.34
True
False

VI. Defining functions  

#定义函数def myfun (x):    if x <=:        print (' less than) '    else:        print (' Greater than ') print (Myfun (30))

Output: Less than 60

1) Define an empty function, and do nothing

Def NOP ():    Pass

The role of pass is to do nothing and error, if there is no pass will be wrong, so pass is to occupy a pit

2) detection of inappropriate parameters

def myfun (x):    If not isinstance (x, (int., float)):        raise TypeError (' bad operand type ')    if x >= 0:        retu RN x    else:        return-x

After the parameter check is added, the function can throw an error if the wrong parameter type is passed in

Output:

Traceback (most recent):  File "/mnt/hgfs/webspace/pythonstudy/one.py", line, <module>    Myfun (' hello ')  File "/mnt/hgfs/webspace/pythonstudy/one.py", line 234, in Myfun    raise TypeError (' bad operand type ') Typeerror:bad operand type

2) return multiple parameters

Import mathdef Move (x, y, step, angle=0):    NX = x + step * math.cos (angle)    NY = y-step * Math.sin (angle)    Retu RN NX, Nyx, y = Move (+, +, MATH.PI/6) print (x, y)

  import mathThe statement represents math the import package and allows subsequent code to reference math the function in the package, sin cos such as

Seven, function parameters

Variable parameters allow you to pass in 0 or any of the parameters, which are automatically assembled as a tuple when the function is called

#函数的参数 # Default parameter, variable parameter # Default parameter does not explain, variable parameter case as follows # mutable parameter is like defining a list or a tuple, just add a *def myfun (*number) to the front of the parameter: for item in number    :        print (item) myfun (111,222,333)

Output:

111
222
333

#关键字参数 # and the keyword parameter allows you to pass in 0 or any parameter with a parameter name that is automatically assembled inside the function as a dictdef myfun (name, age, **kw):    print (' name: ', name)    Print (' Age: ', age)    print (' kw: ', kw) myfun (' CiCi ', Nihao = ' aaaa ')

Output:

Name:cici
Age:18
KW: {' Nihao ': ' AAAA '}

Basic learning of Python (i)

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.