function is a function, a method, simplify the code
def say (name,sex= ' man '): #函数, formal parameters, formal arguments, variables
#name为必填参数, location
#sex为默认值参数, do not pass the default value, not required
Print ('%s ha ha sex%s '% (name,sex)) #函数体
The variables inside the function are all local variables, it can only be used inside the function, and the function execution ends so there is no such variable
Def calc (A, B):
res = A * b
Return res #返回值, the function ends immediately if it encounters a return
If you need to use the result of the function, then write the return, no need, then do not write
def my ():
For I in range (100):
Print (i)
If i==2:
Return
Second, little Practice
EG1: Write a program that verifies whether the input string is a decimal
1, only a decimal point to determine the number of decimal points
2, positive decimals, the left and right of the decimal point is an integer, only legal [0, 12]
3, negative decimal point to the right of the integer, the left must start with a minus sign, only a minus sign.
#-5.4
# ['-5 ', ' 4 ']
# [1:]
def check_float (s):
s = str (s)
If S.count ('. ') ==1:
S_list = S.split ('. ')
left = s_list[0] #小数点左边 # '-98 '
right = S_list[1] #小数点右边
If Left.isdigit () and Right.isdigit (): #这里是判断正小数的
Return True
If Left.startswith ('-') and Left[1:].isdigit () and Right.isdigit ():
Return True
Return False
EG2: Defining read and Write file functions
def my_file (Name,content=none):
With open (name, ' A + ') as F:
F.seek (0)
If content:
F.write (content)
Else
Return F.read ()
#一个函数只做一件事
#重复的代码就是低级的
#实现同样的功能, the less code, the better.
Python Basics (v) function