Python Learning Notes (iv)

Source: Internet
Author: User
Tags ord pow

First, built-in functions

Mathematical operations

ABS (-5) # take absolute value, i.e. 5

Round (2.6) # rounded rounding, which is 3.0

Pow (2, 3) # equivalent to 2**3, if it is POW (2, 3, 5), equivalent to 2**3% 5

CMP (2.3, 3.2) # Compare the size of two numbers

Divmod (9,2) # returns the division result and remainder

Max ([1,5,2,9]) # Ask for maximum value

MIN ([9,2,-4,2]) # to find the minimum value

SUM ([2,-1,9,12]) # sum

Type conversions

Int ("5") # is converted to an integral integer

Float (2) # Convert to floating-point float

Long ("23") # converts to a long integer long

STR (2.3) # converts to string strings

Complex (3, 9) # returns complex number 3 + 9i

Ord ("A") # "a" character corresponding value

Chr (65) # Number 65 corresponds to the character

UNICHR (65) # VALUE 65 corresponds to the Unicode character

BOOL (0) # converted to the corresponding true and False value, in Python, 0 is equivalent to False

In Python, the following objects are equivalent to false: [], (), {}, 0, None, 0.0, "

Bin (56) # Returns a String representing a binary number of 56

Hex (56) # Returns a String that represents the hexadecimal number of 56

Oct (56) # Returns a String that represents the octal number of 56

List (()) # Convert to Table list

Tuple ([2,3,4]) # Convert to fixed value table tuple

Slice (5,2,-1) # Build Subscript Object Slice

Dict (a=1,b= "Hello", c=[1,2,3]) # Build Dictionary Dictionary

Sequence operations

All ([True, 1, "hello!"]) # If all elements are equal to true values

Any (["", 0, False, [], None]) # is there any one element equal to the true value

Sorted ([1,5,3]) # Returns the sequence of the positive sequence, i.e. [1,3,5]

Reversed ([1,5,3]) # Returns the sequence of the reverse order, i.e. [3,5,1]

# anonymous function F=lambda a,b:a+bprint (f (2,3))         # 5 # ABS () take absolute print (ABS ( -111))        # 111 # All () loop to iterate over Every element of the image is true, otherwise it returns false # 0,none, "", [], (), {} is False print (all ([11,22]))    # TRUE&NB sp;# any has a true, all true print (any ([0,0,none]))      #False  # ASCII in the object class Find __repr__, get return value class D ():     def __repr__ (self):         return ' Hello ' D=d () print (ASCII (d))        #hello                                  # bin converts decimal to 2 in # Oct () hex () print (BIN)                                       #0b1011   #各种进制转换成十进制可以用int () print (int (' One ', base=2))          Convert #将二进制 ' 11 ' to 10Number of 3 # bytearry   byte list  # chr () find number for ASCII code # ORD () ASCII code corresponding number # CHR Ord only applies to ASCII code print (CHR (65)) &                                  nbsp;     # Aprint (Ord (' A '))      # 65 # callable is followed by a brace to see if you can execute #complie () to accept a string, convert it to a function code  # divmod return Division (value, remainder) print (Divmod (10,3) )     # (3,1)  # eval calculator function return result print (eval (' a+60 ', {' a ': ') ')   &                        nbsp;     # 150print (eval (' 3+4*6/7+ ((1+2)-5) ')      # 4.428571428571429  #exec, execute Python code, no return value exec ("For I in range (5):p rint (i)")   # Direct Loop output 0,1,2,3,4 # filter (function, iterated object) # Loop can iterate over the object, execute it in the function, if not conforming to filter def fun (s):                  #定义判断一个数是否是偶数的函数      if s%2==0:         return true    else:         return Falseret=filter (fun,[1,2,3,4,5,6,7,8]) for I in Ret:    print (i)                 # Print out 2,4,6,8  #用匿名 function rewrite Ret1=filter (lambda x:x%2==0,[1,2,3,4,5,6,7,8]) for I in Ret1:    print (i)                                         # 2,4 ,6,8  #map将传入的函数依次作用到序列的每个元素 and returns the result as a new iterator Ret=map (Lambda x:x+100,[1,2,3]) for I in ret:     print (i)                                    # 101,102,103 # Globals () get all global variables of the current file # locals ()   Get all local variables of the current file # hash ()   &NB Sp Get hash value # isinstance see if an object is created by a class   #iter () Create an object that can be iterated next () remove a value k=iter ([1,2,3,4]) print (next (k))                     &NB Sp # 1 # POW () Find index print (POW (2,10))           #1024 &nbs p;# round () rounding # #zipl1 =[1,2,3,4]l2=[' A ', ' B ', ' C ', ' d ']k=zip (L1,L2) for I in K:     print (i)                       #打印出 (1,a), (2,b) ....

  

Second, the file operation

Open file--open (' file ' [, ' mode '])

    • R, read-only mode "default"
    • W, write-only mode "unreadable: does not exist, is created; empty content exists;"
    • X, write-only mode "unreadable: not present, created, present error"
    • A, append mode is "unreadable, not present", and only append content;

"+" means that a file can be read and written, such as r+,w+,x+ and A +. "B" means to manipulate RB or R+B,WB or W+B,XB or x+b, AB, or a+b in bytes, when opened in B, the content read is a byte type, and a byte type is required for writing, which requires the programmer to do the conversion itself, which is done from the code.

Common file operation methods:

Method

Describe

F.close ()

Close the file, remember to open the file after opening () must remember to close it, otherwise it will occupy the system open file handle number.

F.name ()

Get file name

F.next ()

Returns the next line and shifts the file action marker to the next line. When a file is used for a statement such as for ... in file, it is called the next () function to implement the traversal.

F.fileno ()

Gets the file descriptor, which is a number. Returns a "file label" for a long integer type

F.flush ()

Refreshes the output cache and writes the contents of the buffer to the hard disk

F.isatty ()

Returns true if the file is a terminal device file (on a Linux system), otherwise false is returned.

F.read ([size])

Read the file, size is the length of the read, in bytes

F.readline ([size])

Reads a line of information, and if size is defined, a portion of the line is read

F.readlines ([size])

Reads all the lines, that is, the information that reads the entire file. (Take each line of the file as a member of a list and return to the list.) In fact, its internal is through the Loop call ReadLine () to achieve. If you provide a size parameter, size is the total length of the read content, which means that it may be read only to a portion of the file)

F.seek (Offset[,where])

Move the file pointer to the offset position relative to where. Where 0 indicates the beginning of the file, this is the default, 1 is the current position, and 2 means the end of the file. (Note: If the file is open in a or a + mode, the file action tag will automatically return to the end of the file each time you write)

F.tell ()

Get the file pointer position, mark the current position, and start with the origin of the file.

F.truncate ([size])

The file is cut to the specified size, the default is the location of the current file operation tag. If the size of the file is larger, depending on the system may not change the file, it may be 0 files to the corresponding size, it may be some random content to add.

F.write (String)

Writes string strings to a file, and write () does not add a newline character after Str.

F.writelines (list)

Writes a string in a list to a file in a row, and writes the file continuously without wrapping.

>>> file=open (' test.txt ') >>> file.read (4)  #读取前4个字节 ' hell ' >>> file.read (6)  # Note that this is the ' O\nworl ' >>> file.read () #不指定size, which is read to the end of the file, after reading the "  D\nhello\npython" >>> File.read ()  #再读时已是文件结尾 ' >>> file.seek (0)  #将文件位置定位到第一个字节 >>> file.readline ()  #一次读一行 ' Hello\n ' >>> file.readline () ' world\n ' >>> file.seek (0)   #将文件定位到开始 >>> file.readlines ()   #读取整个文件的内容 [' hello\n ', ' world\n ', ' hello\n ', ' Python ']>>> file. Tell () #读完之后显示seek位置, that is, the last 27L of the file   # Long-integer >>> file.name   #查看文件的名称 ' test.txt ' >>> file.close () #关闭文件

  

Third, recursion

Inside the function, other functions can be called;
If a function calls itself internally, the function is a recursive function.

Use the function to write the following series:

Fibonacci numbers refer to such a sequence of 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233,377,610,987,1597,2584,4181,6765,10946,17711,28657,46368 ...

The implementation code is as follows:

def func1 (ARG1,ARG2):    if arg1 = = 0:    #print arg1,arg2        pass    arg3 = arg1 + arg2    if Arg3 >:        RE Turn Arg3    return func1 (ARG2,ARG3)   #这里return, all values

  

Python Learning Notes (iv)

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.