Default parameter in function
you can set its default value when you define a function
def power(x, n=2):
s = 1
while n > 0:
n = n - 1
s = s * x
return s
Note: the Mandatory parameter sshould placed in front of the default parameters
Variable parameter
if you add a star * in front of the parameter, this paramtere could be a list of tuple though you may not give it in the list form
def calc(*numbers):
sum = 0
for n in numbers:
sum = sum + n * n
return sum
calc(1,2,3)
Recursive function
def factorial(x):
if x==1:
return 1
else:
return x*factorial(x-1)
Slice
exactly like the function of : in matlab
L=list(range(100))
L[1:10]
List Comprehensions
powerful weapon
you can use it to generate list with the help of for loop
[x*(x-1) for x in range(100) if x%2==0]
网友评论