1. Function definition
A function is a group of statements that accomplishes a particular function, which can be used as a unit and give it a name that can be executed multiple times in different places of the program by the function name (often called a function call)
Why use a function?
Reduce the difficulty of programming, usually a complex big problem decomposition into a series of small problems, and then divide the small problem into a smaller problem, when the problem is refined enough simple, we can divide and conquer, each small problem solved, big problem is solved.
Code reuse, avoid duplication of labor, improve efficiency.
Definition and invocation of functions
def function name ([parameter list])//definition
function name ([parameter list])//Call
Example:
function definition:
def Fun ():
print ("Hello World")
Function call:
Fun ()
Hello World
Examples of scripts:
#/usr/bin/env python
#-*-Coding:utf-8-*-
# @time: 2018/1/2 19:49
# @Author: fengxiaoqing
# @file: int.py
def fun ():
STH = raw_input ("Please input sth:")
Try: #捕获异常
if Type (int (sth)) ==type (1):
Print ("%s is a number")% STH
Except
Print ("%s is not number")% STH
Fun ()
2. Parameters of the function
formal parameters and actual parameters
when a function is defined, the variable name in parentheses is called a formal parameter, or "parameter", after the function name .
when a function is called, the variable name in parentheses is called the actual parameter, or "argument", after the function name .
def fun (x, y)://Parameter
Print x + y
Fun ()//argument
3
Fun (' A ', ' B ')
Ab
3. Default parameters for functions
Practice:
All PID of the printing system
Request read from/proc
Os.listdir () method
#/usr/bin/env python
#-*-Coding:utf-8-*-
# @time: 2018/1/2 21:06
# @Author: fengxiaoqing
# @file:p rintpid.py
Import Sys
Import OS
def isnum (s):
For I in S:
If I not in ' 0123456789 ':
Break #如果不是数字就跳出本次循环
else: #如果for中i是数字才执行打印
Print S
For J in Os.listdir ("/proc"):
Isnum (j)
function Default parameters:
Default parameter (default parameter)
def fun (x,y=100)
Print x, y
Fun ($)
Fun (1)
Definition:
def fun (x=2,y=3):
Print X+y
Call :
Fun ()
5
Fun (23)
26
Fun (11,22)
33
Exercises
1. Design a function to count the number of numeric characters in any string of strings
For example:
"Adfdfjv1jl;2jlk1j2" number is 4
2. Design function, count the number of each letter in any string, case-insensitive
For example:
"Aaabbbcccaae111"
A 5
B 3 x
C 3 x
E One
function definition and parameter examples in Python