Python3 Concise tutorial Study (top)

Source: Internet
Author: User
Tags finally block logical operators pear terminates python list

First, start the Python journey interactive mode

1.Ctrl + D Enter an EOF character to exit the interpreter, or you can type exit () to exit

2. #!/usr/bin/env python3 in #! called Shebang, the purpose is to tell the shell to use the Python interpreter to execute its code below.

3. Observe the following conventions:

    • Use 4 spaces to indent
    • Never Mix spaces and tabs
    • An empty line between functions
    • Empty two lines between classes
    • Dictionary, list, tuple, and parameter list, after, add a space. For dictionaries, a space is added to the following:
    • There are spaces around the assignment operator and the comparison operator (except in the argument list), but no space is added to the brackets: a = f (1, 2) + g (3, 4)

4. The module is a file containing reusable code that contains different function definitions and variables. Module files are usually extended with a. py extension, which is imported before the module is used.

Ii. variables and data types 1. Keywords (cannot be used for usual identifiers)

2. Defining variables

You do not need to specify a data type for a variable, with single or double quotation marks when manipulating strings

3. Reading input from the keyboard
number = int(input("Enter an integer: "))
4. Assign multiple values to multiple variables in one line
>>> a , b = 4, 5>>> a4>>> b5

Create a tuple with commas, create a tuple on the right side of an assignment statement that is a tuple wrapper (tuple packing), and the left side of the assignment statement is a tuple unpacking (tuple unpacking).

Third, operators and expressions

Divmod ()

divmod()The function combines the divisor and remainder operations to return a tuple containing quotient and remainder (a // b, a % b) :

If you now calculate the number of months and days by getting the number of days entered by the user, you can use the function to get to the answer easily:

#!/usr/bin/env python3days = int(input("Enter days: "))print("Months = {} Days = {}".format(*divmod(days, 30)))  用 * 运算符拆封这个元组

Divisible

If you want to divide it, use the//operator, which returns the integer part of the quotient:

Think: If 12 / 3 so, what is the result? People will say is not stupid? It must be 4! Then try it:

It's not the same as what you think! So / whether it's divisible or not, the result is floating-point numbers.

logical operators

The logical operators and and or are also known as short-circuit operators : Their parameters are parsed from left to right, and once the results are determined, they stop. when acting on a normal non-logical value, the return value of the short-circuiting operator is usually the one that can determine the result first.

operator Logical Expressions Description
and X and Y If x is false,x and y returns False, it returns the computed value of Y.
Or X or Y If x is 0, it returns the value of x, otherwise it returns the computed value of Y.
Not Not X If x is True, returns FALSE. If X is False, it returns TRUE.
>>> 5 and 4    (5为True还要往后看,所以最先确定的操作数是4)4>>> 0 and 4    (0为False不需往后看,所以最先确定的操作数是0)0>>> False or 3 or 0   (False还要往后看,3为True不需往后看,所以最先确定的操作数是3)3

Operator Precedence

Type conversions

type conversion, int, float to string with the str() line, it is very easy to understand that the string is a "number" string (' 1234 ') to int well understand, but if it is the string ' a '? Maybe you would think of ASCII, int(‘a‘) can you use it?

The results show that it is not possible, so let's learn more about the bad.

1.十进制字符串转整数int(‘12‘) ==122.十六进制字符转整数int(‘a‘,16) == 10 例MAC地址转整数:a=‘FF:FF:FF:FF:FF:FF‘.split(:)int(a[0],16) = 255int(a[1],16) = 255int(a[2],16) = 255int(a[3],16) = 255int(a[4],16) = 255int(a[5],16) = 2553.字符转整数ord(‘a‘)==974.整数转为字符chr(65) == ‘A‘

Iv. circulation

Range ()

Range () generates a arithmetic progression (not a list):

>>> for i in range(3):...     print(i)...012>>> range(1, 5)      range(1, 5)>>> list(range(1, 5))[1, 2, 3, 4]>>> list(range(1, 15, 3))[1, 4, 7, 10, 13]

The Else statement of the loop

You can use the optional else statement after the loop, which will execute after the loop is complete, unless a break statement terminates the loop.

Fibonacci (Fibonacci) series

When an assignment statement executes in Python, the expression on the right side of the assignment operator is evaluated first , and then the value is assigned to the variable on the left.

What if you want to output the results without a newline? Print () prints a newline character in addition to the supplied string, so each time a print () is called, the line is changed once. You can replace line breaks with the parameter end:

a, b = 0, 1while b < 100:    print(b, end=‘ ‘)    a, b = b, a + bprint()

Power series: E^x = 1 + x + x^2/2! + x^3/3! + ... + x^n/n! (0 < x < 1)

#!/usr/bin/env python3x = float(input("Enter the value of x: "))n = term = num = 1result = 1.0while n <= 100:    term *= x / n    result += term    n += 1    if term < 0.0001:        breakprint("No of Times= {} and Sum= {}".format(n, result))

Print graphics

print("#" * 50)If a string is multiplied by an integer n, it returns a new string that is stitched together by N of this string. To print out:

row = int(input("Enter the number of rows: "))n = rowwhile n >= 0:    x = "*" * n    y = " " * (row - n)    print(y + x)    n -= 1
V. Data structure

List

Lists can be written in parentheses between a column of comma-separated values. The elements of a list do not have to be of the same type, and each value in the list is accessed through an index, and the list allows elements to be modified, allowing nesting.

a.append() 添加元素到列表的末端 a.insert(0, 1) 在列表索引 0 位置添加元素 1a.count(s) 返回列表中 s 元素出现的次数。a.remove(s) 移除列表中s元素a.pop(n)  返回索引为n的元素并把它从列表中删除,无参数时默认最后一个元素del a[n] 删除索引为n的列表元素a.reverse() 反转整个列表a.sort() 给列表排序,排序的前提是列表的元素是可比较的a.extend(b) 将b列表的所有元素添加到a列表末尾,注意是添加 b 的元素而不是 b 本身


thinking: If the list has the same element, remove with remove is the front or the back, or delete it all? Practice a bit!

A list derivation consists of brackets that contain an expression followed by a for clause, followed by 0 or more for or if clauses. The result is a list of the results made by the expression based on the context of the for and if clauses behind it. The following two ways are equivalent:

List derivations can also be nested:

>>> a=[1,2,3]>>> z = [x + 1 for x in [x ** 2 for x in a]]>>> z[2, 5, 10]

If you get the index value of an element while traversing the list (or any sequence type), you can use enumerate() :

>>> for i, j in enumerate([‘a‘, ‘b‘, ‘c‘]):...     print(i, j)...0 a1 b2 c

Traversing two sequence types at the same time can be used zip() :

>>> a = [‘a‘, ‘b‘]>>> b = [‘c‘, ‘d‘]>>> for x, y in zip(a, b):...     print("{} and {}".format(x, y))

Ganso

Tuples are made up of several comma -separated values and are immutable types, meaning that you cannot delete or add or edit any values within a tuple.

>>> a = ‘a‘, ‘b‘, ‘c‘,>>> a(‘a‘, ‘b‘, ‘c‘)

Create a tuple that contains only one element, followed by a comma after the value, because parentheses () can represent both tuples and parentheses in mathematical formulas, which creates ambiguity.

>>> a = (123)     这样定义的将是123这个元素,而不是一个元组。 >>> a123>>> type(a)<class ‘int‘>>>> a = (123, )>>> b = 321,>>> a(123,)>>> b(321,)>>> type(a)<class ‘tuple‘>>>> type(b)<class ‘tuple‘>

You can perform a tamper operation on any one tuple and assign a value to multiple variables, noting that the number of assignments is matched:

Collection

A collection is a set of unordered, non-repeating elements that can be used to create a collection

>>> basket = {‘apple‘, ‘orange‘, ‘apple‘, ‘pear‘, ‘orange‘, ‘banana‘}>>> print(basket)                      可以看到重复的元素被去除{‘orange‘, ‘banana‘, ‘pear‘, ‘apple‘}>>> a = set(‘abracadabra‘)>>> b = set(‘alacazam‘)>>> a                                  {‘a‘, ‘r‘, ‘b‘, ‘c‘, ‘d‘}              a 去重后的字母>>> a - b                              a 有而 b 没有的字母>>> a | b                              存在于 a 或 b 的字母>>> a & b                              a 和 b 都有的字母>>> a ^ b                              存在于 a 或 b 但不同时存在的字母>>> a.add(‘c‘)>>> a{‘c‘,a‘, ‘r‘, ‘b‘, ‘c‘, ‘d‘}          不同于列表的append(),在起始位置添加

Dictionary

The dictionary is an unordered set of key-value pairs (key:value), and the keys within the same dictionary must be distinct from each other. A pair of curly braces {} Creates an empty dictionary. The key in the dictionary must be an immutable type, such as a list cannot be used as a key.

>>> data = {‘kushal‘:‘Fedora‘, ‘kart_‘:‘Debian‘, ‘Jace‘:‘Mac‘}>>> data[‘kart_‘]‘Debian‘>>> data[‘parthan‘] = ‘Ubuntu‘           创建新的键值对>>> data{‘kushal‘: ‘Fedora‘, ‘Jace‘: ‘Mac‘, ‘kart_‘: ‘Debian‘, ‘parthan‘: ‘Ubuntu‘}>>> del data[‘kushal‘]                   del 删除任意指定的键值对>>> data{‘Jace‘: ‘Mac‘, ‘kart_‘: ‘Debian‘, ‘parthan‘: ‘Ubuntu‘>>> dict(((‘In‘,‘Del‘),(‘Bang‘,‘Dh‘)))   dict() 从包含键值对的元组中创建字典{‘In‘: ‘Del‘, ‘Bang‘: ‘Dh‘}>>> for x, y in data.items():            items()获得由键和值组成的列表...     

Many times you need to add data to the elements in the dictionary , using dict.setdefault(key, default) :

>>> data = {}>>> data.setdefault(‘names‘, []).append(‘Ruby‘)>>> data{‘names‘: [‘Ruby‘]}>>> data.setdefault(‘names‘, []).append(‘Python‘)>>> data{‘names‘: [‘Ruby‘, ‘Python‘]}>>> data.setdefault(‘names‘, []).append(‘C‘)>>> data{‘names‘: [‘Ruby‘, ‘Python‘, ‘C‘]}

See MORE:
List in Python, tuple (tuple), dictionary (Dict) and collection (set), Python list, tuple, collection, dictionary differences and mutual conversions

Slice

The syntax expression for a slice is [start_index : end_index : step] :

    • Start_index represents the starting index
    • End_index = End Index
    • Step indicates step size cannot be 0, and the default value is 1

A slice operation is a step that intercepts all elements from the starting index to the end index, but not the end index .

    • Python3 data types that support slicing operations are list, tuple, string, Unicode, range
    • The result type returned by the slice is consistent with the original object type
    • Slices do not change the original object, but instead regenerate a new object

The index of a slice can be divided into two positive and negative ways:

As an example:

>>> C = [‘A‘,‘B‘,‘C‘,‘D‘,‘E‘,‘F‘]>>> C[0:5:1][‘A‘, ‘B‘, ‘C‘, ‘D‘,‘E‘]

Omitting Start_index begins with the first element, and omitting end_index cuts to the last element :

>>> C[2:][‘C‘, ‘D‘, ‘E‘, ‘F‘]

Step is negative when the inverse of the cut, it is necessary to ensure that the direction of Start_index to End_index and step step direction, otherwise it will cut out the empty sequence:

>>> C[0:3:-1][]>>> C[3:0:1][]

Examples of data structures

1. Determine whether the student's performance is standard: the number of students required to enter, as well as the students of physics, mathematics, history of the three subjects, if the total score is less than 120, the program print "failed", otherwise print "passed".

n = int(input("Enter the number of students: "))data = {}  用来存储数据的字典变量Subjects = (‘Physics‘, ‘Maths‘, ‘History‘) for i in range(1, n+1):    name = input(‘Enter the name of the student {}: ‘.format(i))      marks = []    for x in Subjects:        marks.append(int(input(‘Enter marks of {}: ‘.format(x))))      data[name] = marksfor x, y in data.items():    total =  sum(y)    print("{}‘s total marks {}".format(x, total))    if total < 120:        print(x, "failed :(")    else:        print(x, "passed :)")

Run as follows:

2. Use the following code to solve the matrix problem :

n = int(input("Enter the value of n: "))print("Enter values for the Matrix A")a = []for i in range(n):    a.append([int(x) for x in input().split()])print(a)

In fact, this is not very understanding why the final result is a list of nested lists (str.split(str="", num=string.count(str)),str -- 分隔符,默认为所有的空字符,包括空格、换行(\n)、制表符(\t)等,num -- 分割次数) , and thought this is the matrix to generate NXN, so the following practices :

As you can see, split () is finally broken into a list, ending a loop with a newline character, not a matrix that generates NXN. In relation to split (), join () joins multiple strings using the specified character, which requires a list of string elements as input, and then joins the string elements in the list:

>>> "-".join("GNU/Linux is great".split())基于空格分割字符串(列表),再用 "-" 连接‘GNU/Linux-is-great‘
Six, string

Three quotation marks (triple quotes)

Python three quotes allow a string to span multiple lines, and the string can contain line breaks, tabs, and other special characters.

 >>> h = ‘‘‘hi Jspo‘‘‘>>> hi   ‘hi\nJspo‘>>> print hi  hi Jspo  

Three quotes allow programmers to escape from the mire of quotes and special strings, keeping a small piece of string in the form of what is known as WYSIWYG. A typical use case is that when a piece of HTML or SQL is needed, a special string escape will be cumbersome when combined with a string.

In addition, the document string (docstrings) is used in Python to illustrate how to use the code:

def longest_side(a, b):    """    Function to     """    return True

String Common operations

string.title() 返回字符串的标题版本,即单词首字母大写其余字母小写string.upper() 返回字符串全部大写版本string.lower() 返回字符串全部小写版本 string.swapcase() 返回字符串大小写交换后的版本 string.isalnum()  检查所有字符是否为字母数字string.isalpha()  检查字符串之中是否只有字母string.isdigit()  检查字符串是否所有字符为数字

strip (chars) is used to Peel The characters specified in the end of a string, without specifying a parameter, by default stripping out the leading and trailing blanks and line breaks . Use Lstrip (chars) or Rstrip (chars) to split only the string left or right:

>>> s = "www.foss.in" >>> s.lstrip("cwsd.") 删除在字符串左边出现的‘c‘,‘w‘,‘s‘,‘d‘,‘.‘字符‘foss.in‘>>> s.rstrip("cnwdi.") 删除在字符串右边出现的‘c‘,‘n‘,‘w‘,‘d‘,‘i‘,‘.‘字符‘www.foss‘

Text Search

Find () can help locate the first matched substring, and 1 is returned without a find.string.find(str, beg=0, end=len(string))
Detects if STR is contained in a string, if beg and end specify a range, the check is contained within the specified range, or 1 if the index value is returned.

s.startswith(str)  检查字符串是否以 str 开头s.endswith(str)    检查字符串是否以 str 结尾

String more operations See: Python string

Example ( Challenge: string manipulation )

String.txt the contents of the file are awe3fa8fa4aewfawijfa;fjaweawfeawawefargaefaef5awefasdfeargfasdcds2awea4afadszsdvzxefafzsdva7fasdczdvafedszv6zvczvdsf2awefafzsdccsea , please make a new string of all the numbers in the file, and print them out.

Note: Learn the following lessons to find this challenge without closing the file (File.close ()), to develop a habit, otherwise remember to use with!

Seven, function
def 函数名(参数列表):    函数体

Return without an expression is equivalent to returning None.

Parameter passing

In Python, a type belongs to an object, and a variable has no type . a=[1,2,3]和a="Jspo"for example, [All-in-one] is a list type, "Jspo" is a string type, and variable A is no type, just a reference to an object ( a stylus), either to a list type object or to a string type object.

In Python, strings, tuples, and numbers are objects that cannot be changed , and List,dict are objects that can be modified .

    • Immutable type: Variable assignment a=5 and then assign value a=10, here is actually reborn into an int value object 10, then let a point to it, and 5 is discarded, not change the value of a, the equivalent of a new born into a
    • Variable type: variable assignment la=[1,2,3,4] After assigning a value la[2]=5 is to change the value of the third element of List LA, itself la does not move, but its internal part of the value has been modified

Parameter passing of the Python function:

    • Immutable types: Similar value passes, passing only the value of a, without affecting the A object itself (added to the global global variable)
    • mutable types: Similar to reference passing

Parameter type

    • Required Parameters: The function is passed in the correct order, and the number of calls must be the same as when declared
    • Keyword parameters: Shape keyword = value , use keyword arguments to allow a function call when the order of the arguments is inconsistent with the Declaration, because the Python interpreter can match parameter values with argument names

    • Default parameters: When a function is called, if no arguments are passed, the default parameters are used, and the default parameters must be placed last . If the caller does not give a value of B, C, then their value defaults to 5 and 10

    • Variable length parameter: A function is required to handle more arguments than was originally declared. These parameters are called variable length parameters, and are not named when declared

Say a few words to the indefinite length parameter: The variable name with an asterisk (*) holds all the unnamed variable arguments and cannot hold dict. A variable name with an asterisk (* *) holds all the unnamed variable arguments (it is an empty element if no arguments are specified when the function is called). As an example:

def multiple(arg, *args, **dictargs):    print("arg: ", arg)    #打印args    for value in args:        print("other args:", value)    #打印dict类型的不定长参数 args    for key in dictargs:        print("dictargs:" + key + ":" + str(dictargs[key]))if __name__ == ‘__main__‘:    multiple(1,‘a‘,True, name=‘Amy‘,age=12)

Higher order functions

Map takes a function and a sequence (iterator) as input, and then applies the function to each value of the sequence (iterator), returning a sequence (iterator) that contains the result after applying the function.

>>> lst = [1, 2]>>> def s(num):...     return num * num...>>> print(list(map(s, lst)))[1, 4]

Note: Don't forget to add list! before map

Viii. Processing of documents

Common operations

To open a file using the open () function, you need two parameters, the first parameter is the file path or filename, and the second is the open mode of the file:

    • "R", open in read-only mode, you can only read the file but cannot edit/delete any contents of the file
    • "W", open in write mode, if the file exists will delete everything inside, then open this file for writing
    • "A", open in Append mode, any data written to the file will be automatically added to the end

Examples

Example 1: copying a given text file to another given text file:

import sysif len(sys.argv) < 3:    print("Wrong parameter")    print("./copyfile.py file1 file2")    sys.exit(1)f1 = open(sys.argv[1])s = f1.read()f1.close()f2 = open(sys.argv[2], ‘w‘)f2.write(s)f2.close()

SYS module: SYS.ARGV contains all command-line arguments.
The first value of a SYS.ARGV is the name of the command itself:

import sysprint("First value", sys.argv[0])print("All values")for i, x  in enumerate(sys.argv):    print(i, x)

Enumerate (Iterableobject) can get the index position and corresponding value at the same time.

Example 2: count tabs, lines, and spaces in any given text file.

import osimport sysdef parse_file(path):        fd = open(path)    i = 0    spaces = 0    tabs = 0    for i,line in enumerate(fd):        spaces += line.count(‘ ‘)        tabs += line.count(‘\t‘)    # 现在关闭打开的文件    fd.close()    # 以元组形式返回结果    return spaces, tabs, i + 1def main(path):      if os.path.exists(path):        spaces, tabs, lines = parse_file(path)        print("Spaces {}. tabs {}. lines {}".format(spaces, tabs, lines))        return True    else:        return Falseif __name__ == ‘__main__‘:    if len(sys.argv) > 1:        main(sys.argv[1])    else:        sys.exit(-1)    sys.exit(0)

Small tips:

If you want to count the number of lines in a file, you can use it, although it is count = len(open(filepath, ‘r‘).readlines()) simple, but it may be slow, even if the file is larger. So you can use enumerate ():

count = 0for index, line in enumerate(open(filepath,‘r‘)):     count += 1

In addition, using the WITH statement to process a file object will automatically close when the file is exhausted, even if an exception occurs. It is shorthand for the try-finally block:

with open(‘sample.txt‘) as f:    for line in f:        print(line, end = ‘‘)
Nine, abnormal
    • Using Python2 's unique syntax in Python3 will occur syntaxerror
    • Nameerror occurs when someone tries to access an undefined variable
    • When an operation or function is applied to an object of an inappropriate type, a common example is the addition of integers and strings typeerror

Try--except

    • First, the TRY clause is executed, and if no exception occurs, the EXCEPT clause is ignored after the try statement has finished executing.
    • If an exception occurs during the execution of a try clause, the remainder of the clause is ignored.
    • If the exception matches the exception type specified after the except keyword, the corresponding except clause is executed. Then continue executing the code after the try statement.
    • If an exception occurs, there is no branch in the except clause that matches it, and it is passed to the upper-level try statement.
    • If the corresponding processing statement is still not found, it becomes an unhandled exception, terminates the program run, and displays a prompt message.

Except can handle a specialized exception, or it can handle an exception in a set of parentheses, and if no exception is specified after except, all exceptions are handled by default.

Raise

The Raise statement throws an exception. such as " Challenge: Play function " requires the user to be able to enter the number of minutes from the command line, the program needs to print out the corresponding hours and minutes. If the user enters a negative value, the program needs an error valueerror, printing on the screen ValueError: Input number cannot be negative prompts the user to enter the wrong values.

import sysdef ToHours(time):    print("{} H, {} M".format(*divmod(time, 60)))time =int (sys.argv[1])if time < 0:    try:        raise ValueError    except ValueError:        print("ValueError: Input number cannot be negative")else:    ToHours(time)

Finally

Whether or not an exception occurs, the finally clause is bound to be executed after the program leaves the try. When a try statement occurs in an exception that is not caught by except (or if it occurs in the except or else clause), it is re-thrown after the finally clause finishes executing:

>>> try:...     raise KeyboardInterrupt... finally:...     print(‘Goodbye, world!‘)...Goodbye, world!KeyboardInterruptTraceback (most recent call last):  File "<stdin>", line 2, in ?

In real-world scenarios, the finally clause is used to free external resources (files or network connections, and so on), regardless of whether they were used in error.

Python3 Concise tutorial Study (top)

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.