About bloggers : Former Internet manufacturer tencent staff , Network security giant Venustech staff , Alibaba cloud development community expert blogger , WeChat official account java Quality creators of basic notes ,csdn High quality creative bloggers , Entrepreneur , Knowledge sharers , Welcome to your attention , give the thumbs-up , Collection .
In the actual development process , You will often encounter many identical or very similar operations , At this time , Code that implements similar operations can be encapsulated as functions , Then call the function where you need it . This can not only realize code reuse , It can also make the code more organized , Increase code reliability . Now let's introduce python The return value of the function .
example : Write a function to find the smaller of the two numbers .
def minimal(x, y): # Custom calculate small value function
if x > y: # If x>y establish , return y Value
return y
else: # Otherwise return to x Value
return x
a = float(input(' Enter the first data :')) # Display prompt and receive a Value
b = float(input(' Enter the second data :')) # Display prompt and receive b Value
c = minimal(a, b) # Call function , Assign a smaller value to c
print(' The smaller value is :',c) # Output c Value
give the result as follows .
If the function does not return sentence ,Python The function will be considered as return None end , Return null value . Function can also be used return Statement returns multiple values , Multiple values are saved as tuples .
example : Programming , A string is required , Calculate the number of upper and lower case letters in the string and output , The calculation process is realized by functions .
def demo(s): # Defined function
a = 0 # Variable a Used to store the number of upper case letters
b = 0 # Variable b Used to store the number of lowercase letters
for ch in s: # Loop through each letter in the string
if ch.isupper(): # call isupper() Method to determine whether it is a capital letter
a += 1 # If it is a Add 1
elif ch.islower(): # call islower() Method to determine whether it is a lowercase letter
b += 1 # If it is b Add 1
return a,b # return a and b Value
s = input(' Please enter the string ') # Input string
c = demo(s) # The call function returns a and b The value of is given to the variable c
print(c,type(c)) # Output variables c And variables c The type of
print(' The number of capital letters is :',c[0],', The number of lowercase letters is :',c[1])# Output results
give the result as follows .
1、 Liao Xuefeng's official website
2、python Official website
3、Python Programming case tutorial
The above is about Python Knowledge about the return value of the function , You can refer to it , If you think it's good , Welcome to thumb up 、 Collection 、 Looking at , Welcome to wechat search java Basic notes , Relevant knowledge will be continuously updated later , Make progress together .