python summary

1. Get the current working directory of python IDLE:

1  import os
 2 os.getcwd()

2. Change the current working directory (you need to add "r" in front of the directory, otherwise a syntax error will be reported):

os.chdir(r " working directory " )

3. Run a function in xxx.py:

1  from xxx import func_name #xxx does not need to include the extension .py
 2 func_name() #call it directly

4. Empty function

def func_name():
     pass   #pass is a placeholder for handling unwritten functions

5. Data type checking can use the function isinstance() to check the parameter type, only parameters of integer and floating-point type are allowed

def my_abs(x):
    if not isinstance(x, (int, float)):
        raise TypeError('bad operand type')
    if x >= 0:
        return x
    else:
        return -x

 6. Define a function with variable parameters:

1  def calc(*numbers): #Add a "*" before the parameter, the calling function can directly input calc(3,4,1,2) 
2      sum = 0
 3      for n in numbers:
 4          sum = sum + n * n
 5      return sum

7. Keyword Parameters

Variable parameters allow 0 or any parameters to be passed in. These variable parameters are automatically assembled into a tuple when the function is called, while keyword parameters allow 0 or any parameters with parameter names to be passed in. These parameters are inside the function Automatically organized as a dict.

def person(name, age, **kw):
    print('name:', name, 'age:', age, 'other:', kw)

>>> person('Bob', 35, city='Beijing')
name: Bob age: 35 other: {'city': 'Beijing'}

>>> extra = {'city': 'Beijing', 'job': 'Engineer'} #还可以这样调用 >>> person('Jack', 24, **extra) name: Jack age: 24 other: {'city': 'Beijing', 'job': 'Engineer'}

8. When python defines a function, 5 parameters can be used in combination at the same time (parameter combination), and the combination order must be: required parameter, default parameter, variable parameter, named keyword parameter, keyword parameter.

9. Modify the following product function to accept one or more numbers and compute the product:

 1 def product(x,y):
 2     return x*y
 3 
 4 
 5 #改为
 6 def product(*kw):
 7     pro = 1 
 8     for i in kw:
 9         pro = pro * i
10     return pro

Note the syntax for defining variadic and keyword arguments:

*argsis a variable parameter, and args receives a tuple;

**kwis a keyword parameter, and kw receives a dict.

And the syntax for how to pass in variadic and keyword arguments when calling a function:

Variable parameters can be directly passed in: func(1, 2, 3), or you can assemble a list or tuple first, and then *argspass in: func(*(1, 2, 3));

Keyword arguments can either be passed in directly: func(a=1, b=2), or you can assemble the dict first, and then **kwpass in: func(**{'a': 1, 'b': 2}).

10. Recursive function

Tower of Hanoi:

1  Move Tower of Hanoi with a recursive function:
 2  def move(n, a, b, c):
 3      if n == 1 :
 4          print ( ' move ' , a, ' --> ' , c)
 5      else :
 6          move(n-1 , a, c, b)
 7          move(1 , a, b, c)
 8          move(n-1 , b, a, c)
 9  
10 move(4, ' A ' , ' B ' , ' C ' )

 11. Iterate dict:

1 d={ " a " :3, " b " :2, " c " :6 }
 2  for key in d: #Iterate key value
 3      print (key)
 4  
5  for value in d.values(): #Iterate value value
 6      print (value)
 7  
8  for k,d in d.items(): #Iterate key and value value
 9 at the same time      print (k,d)

12. The python built-in function enumerate can turn lists and tuples into index-element pairs, so that the index and the element itself can be iterated at the same time in the for loop:

1 d=[(2,3),(4,5),(1,2)]
2 for i,value in enumerate(d):
3     print(i,value)

13. The list generation statement is very concise, and a list object can be generated in one sentence:

[x*x for x in range(1,11)]

 14. Yang Hui triangle generator

 1 def triangles(lines):
 2     L=[]
 3     if lines == 0:
 4         yield L
 5     else:
 6         L=[1]
 7         i=1
 8         yield L
 9         while i<lines:
10             L=[sum(i) for i in zip([0]+L,L+[0])]
11             i=i+1
12             yield L

Refer to https://blog.csdn.net/zmy_3/article/details/51173580 The zip function used in this article has been slightly modified.

What I didn't understand at first was the 10th line of code. The addition of two lists is a merger. After understanding this, it is easy to understand the code in the reference link.

 15. Use map()the function to change the non-standard English name input by the user into uppercase first letter and other lowercase standard names.

1 def normalize(name):
2     return(name.capitalize())
3 
4 
5 l1=["xiaoming","dagou","john"]
6 l2=list(map(normalize,l1))

['Xiaoming', 'Dagou', 'John']#输出结果

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325096000&siteId=291194637