Python function and control statement usage example analysis

PHPz
Release: 2023-05-18 20:37:49
forward
1237 people have browsed it

Function

"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)
Copy after login

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).

Python function and control statement usage example analysis

Judgment

The judgment statement format of Python is as follows:

if condition:
  do
else:
  do
# 注意:冒号和缩进不要忘记了

# 再看一下多重条件的格式
if condition:
  do
elif condition:
  do
else:
  do
Copy after login

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('不合格')
Copy after login

Loop

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
Copy after login

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
Copy after login

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)
Copy after login

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!

Related labels:
source:yisu.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!