Python Basics (v) function

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.