1 #-*-coding:utf-8-*-2 Print("#1. Functions")3 defmy_abs (x):4 ifx>=0:5 returnx;6 Else:7 return-x;8 Print(My_abs (-10))9 Ten #Recursive Functions One Print("#2. Recursive functions") A deffact (n): - ifN==1: - return1; the returnN*fact (n-1); - - Print(Fact (4)) - + #3. Slicing: taking elements - Print("#3. Slicing") +L = List (range (100)) A Print(l[10:20]); at - #4. Iteration: In Python, the iteration is done through the for ... in. - Print("#4. Iteration") - -e={'a': 1,'b': 2,'C': 3,'D': 4} - forKeyinche: in Print(Key) - Print('------------------') to forEinch 'ABCD': + Print(e) - the #5. List generation: List comprehensions, which is a very simple and powerful built-in Python build that can be used to create lists. * Print("#5. List-generated") $ Panax NotoginsengL=[] - forXinchRange (2,10): theL.append (x*x) + Print(L) A the #6. Generator + Print("#6. Generator") -L=[x*x forXinchRange (10)] $ Print(L) $ Print("---Fibonacci sequence------") - defFB (max): -n,a,b=0,0,1 the whilen<Max: - Print(b)Wuyia,b=b,a+b theN=n+1 - return ' Done' Wu Print(FB (5)) - About #7. Iterators $ Print("#7. iterators") - fromCollectionsImportiterable - Print(Isinstance ([], iterable))
View Code
Operating effect:
# 1. Function #2. Recursive function #3. Slices [Ten, one, one,, +, +, +, +, +]# 4. Iterative ABCD------------------abcd#5. List-generated [4, 9, 16, 25, 36, 49 , up, Bayi]#6. Generator [0, 1, 4, 9, +,,, +,, Bayi]---Fibonacci sequence------11235D One#7. Iterator True
Python code exercise (one hour per day)