python函数
2018-05-25 本文已影响0人
esskeetit
Gather Positional Arguments with *
def print_args(*args):
print(type(args))
print('Positional args:', args)
print_args(1,2,3,'hello') #<class 'tuple'>
#Positional args: (1, 2, 3, 'hello')
Gather Keyword Arguments with **
def print_kwargs(**kwargs):
print (type(kwargs))
print('Keyword args:', kwargs)
print_kwargs(first = 1,second = 2) #<class 'dict'>
#Keyword args: {'first': 1, 'second': 2}
def print_all_args(req1, *args, **kwargs):
print('required arg1:', req1)
print('Positional args:', args)
print('Keyword args:', kwargs)
print_all_args(1,2,3,s='hello') #required arg1: 1
#Positional args: (2, 3)
#Keyword args: {'s': 'hello'}
Docstrings
def print_if_true(thing, check):
'''
代码注释
'''
if check:
print(thing)
# Use help to get the docstring of a function
help(print_if_true)
print(print_if_true.__doc__)
Lambda
def binary_operation(func,op1,op2):
return func(op1,op2)
binary_operation(lambda op1,op2: op1 * op2, 2, 4)
Switch Case ??
def zero():
print("You typed zero.\n")
def sqr():
print("n is a perfect square\n")
def even():
print("n is an even number\n")
def prime():
print ("n is a prime number\n")
options = {0 : zero,
1 : sqr,
4 : sqr,
9 : sqr,
2 : even,
3 : prime,
5 : prime,
7 : prime,}
对比
count=0
while count < 11:
print("while count:",count)
count = count + 1
if(count == 11):
break
else:
print("else:",count) #不会执行
count=0
while count < 11:
print("while count:",count)
count = count + 1
else:
print("else:",count) #会执行
while loop&for loop
作用域
x = 1
def change_x():
x = 5 # Try to change x within a function
print(x)
print(x) #1
change_x() #5
print(x) #1
-----------------------------------------------------
x = 1
def change_x():
global x # Try to change x within a function
x=5
print(x)
print(x) #1
change_x() #5
print(x) #5
import module
import report #report.py
report.get_data() #get_data()是report.py中的函数
import rp #report.py
rp.get_data() #get_data()是report.py中的函数
from report import get_data,get_info
get_data()
get_info()
from report import get_data as gdata
get_data()
from source import daily,weekly #source是文件夹 daily.py,weekly.py
daily.forcast()
weekly.forcast()
module search path
import sys
print(sys.path)