Today we briefly talk about Python functions and control statements. The outline is as follows:
"Let the dirty work be done by the function", first of all, let's look at the method of defining functions in Python.
def function name (parameter 1, parameter 2...): return'result'
Functions are used to deal with repetitive things, for example, to find the area of a right-angled triangle, each time we have to define two right-angled sides and a calculation formula. By defining the function, the area function of the right triangle can be calculated by only inputting the right-angled side:
def function(a,b): return '1/2*a*b' #You can also write like this def function(a,b): print( 1/2*a*b)
Don't be too entangled in the difference, using return is to return a value, and the second is to call a function to perform the printing function. Enter function(2,3) to call the function to calculate the area of a right-angled triangle whose right-angle sides are 2 and 3.
Python's judgment statement format is as follows:
if condition: do else: do # Note: Don’t forget the colon and indentation # Look at the format of multiple conditions if condition: do elif condition: do else: do
Here, we give a score and return its score.
a = 78 if a >= 90: print('Excellent') elif a>=80: print('good') elif a>=60: print('qualified') else: print('Unqualified')
Python loop statements include for loop and while loop, as shown in the following code.
#for loop for item in iterable: do #item means element, iterable is collection for i in range(1,11): print(i) #The result is to output 1 to 10 in turn, remember that 11 is not output, and range is a Python built-in function. #while loop while condition: do
For example, design a small program to calculate the sum of 1 to 100:
i = 0 sum = 0 while i <100: i = i + 1 sum = sum + i print(sum) # result 5050
Finally, when loop and judgment are used in combination, you need to learn the usage of break and continue. Break is to terminate the loop, and continue is to skip the loop and continue the loop.
for i in range(10): if i == 5: break print(i) for i in range(10): if i == 5: continue print(i)