Home > Article > Backend Development > Python function and control statement usage example analysis
"Leave the dirty work to functions", first, let's take a look at how to define functions in Python.
def Function name (parameter 1, parameter 2...):
return 'result'
The main purpose of the function is to handle recurring tasks. For example, calculating the area of a right triangle requires defining two right sides and the corresponding formula. Define a function to calculate the area of a right triangle by inputting the length of the right side.
def function(a,b): return '1/2*a*b' #也可以写出这样 def function(a,b): print( 1/2*a*b)
Don’t worry too much about their differences. Using return returns a value, while the second one calls the function and performs the printing operation. You can call a function to calculate the area of a right triangle with sides 2 and 3 by entering function(2,3).
The judgment statement format of Python is as follows:
if condition: do else: do # 注意:冒号和缩进不要忘记了 # 再看一下多重条件的格式 if condition: do elif condition: do else: do
Here, we give a score and return its score.
a = 78 if a >= 90: print('优秀') elif a>=80: print('良好') elif a>=60: print('合格') else: print('不合格')
Python’s loop statements include for loops and while loops, as shown in the following code.
#for循环 for item in iterable: do #item表示元素,iterable是集合 for i in range(1,11): print(i) #其结果为依次输出1到10,切记11是不输出的,range为Python内置函数。 #while循环 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 using loops and judgments together, you need to learn the usage of break and continue. Break is to terminate the loop. , and continue skips this loop and then continues the loop.
for i in range(10): if i == 5: break print(i) for i in range(10): if i == 5: continue print(i)
The above is the detailed content of Python function and control statement usage example analysis. For more information, please follow other related articles on the PHP Chinese website!