程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Python process control Python if else conditional statement explanation

編輯:Python

The code we saw earlier is executed in sequence , That is to say, the first step is to execute the first step 1 statement , And then there's the 2 strip 、 The first 3 strip …… Until the last sentence , This is called sequential structure .

But in many cases , Sequence structured code is not enough , For example, a program is limited to adults only , Children are not old enough , No permission to use . At this point, the program needs to make a judgment , See if the user is an adult , And give tips .

stay  [Python]  in , have access to if else Statement to judge the condition , Then execute different code according to different results , This is called a selective structure or branching structure .

Python Medium if else Statements can be broken down into three forms , Namely if sentence 、if else Statement and if elif else sentence , Their syntax and execution flow are shown in table 1 Shown .

[ Failed to transfer the external chain picture , The origin station may have anti-theft chain mechanism , It is suggested to save the pictures and upload them directly (img-j9MX89Rm-1644827498023)(https://upload-images.jianshu.io/upload_images/27509882-d33434315b541c67.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)]
Of the above three forms , The second and third forms are interlinked , If elif The block does not appear , It becomes the second form . in addition ,elif and else Can't be used alone , It has to be with if Come together , And pair it right .

An explanation of grammatical forms :

  • “ expression ” It can be a single value or variable , It can also be a complex statement made up of operators , There is no limit to form , As long as it gets a value . No matter “ expression ” What kind of results are ,if else Whether or not it holds ( True or false ).
  • “ Code block ” Consists of several statements with the same indent .
  • if、elif、else There is a colon at the end of every sentence :, Don't forget it .

Once an expression holds ,Python It will execute the corresponding code block after it ; If all expressions don't hold , Then perform else The following code block ; without else part , Then do nothing . Last , If you don't have a lot of time , And want to quickly python Improve , The most important thing is not afraid of hardship , I suggest you can put up a letter ( Homophone ):276 3177 065 , That's really good , A lot of people are making rapid progress , I need you not to be afraid of hardship ! You can take a look at it ~, Including a copy compiled by Xiaobian 2022 Abreast of the times Python Information and 0 Introduction to Basics , Welcome to junior and advanced students . In not busy time I will give you the solution

The simplest form of execution is the first form —— only one if part . If the expression holds ( really ), Just execute the following code block ; If the expression doesn't hold ( false ), Just do nothing .

For the second form , If the expression holds , Is executed if The code block that follows 1; If the expression doesn't hold , Is executed else The code block that follows 2.

For the third form ,Python It will judge whether the expression is true from top to bottom , Once you come across a valid expression , Just execute the following block of statements ; here , The rest of the code is no longer executed , Whether the following expression holds or not . If all the expressions don't hold , Is executed else The following code block .

In total , No matter how many branches there are , Can only execute one branch , Or none of them , Multiple branches cannot be performed at the same time .

【 example 1】 Use the first selection structure to determine whether the user meets the criteria :


1. age = int( input(" Please enter your age :") )
3. if age < 18 :
4. print(" You're underage , It is recommended to use the software with family members !")
5. print(" If you have the consent of your parents , Please ignore the above tips .")
7. # The statement does not belong to if Code block for
8. print(" The software is in use ...")

Running results 1:

Please enter your age :16
You're underage , It is recommended to use the software with family members !
If you have the consent of your parents , Please ignore the above tips .
The software is in use …

Running results 2:

Please enter your age :24
The software is in use …

As you can see from the results , If the entered age is less than 18, Is executed if Statement block after ; If the entered age is greater than or equal to 18, No execution if Statement block after . The sentence block here is two of the four spaces indented print() sentence .

【 example 2】 Improve the code above , Exit the program when you don't meet your age :


1. import sys
3. age = int( input(" Please enter your age :") )
5. if age < 18 :
6. print(" Warning : You're underage , You can't use the software !")
7. print(" Minors should study hard , Go to a good University , Serve the motherland .")
8. sys.exit()
9. else:
10. print(" You are an adult , You can use the software .")
11. print(" Precious time , Please don't waste too much time on the software .")
13. print(" The software is in use ...")

Running results 1:

Please enter your age :16
Warning : You're underage , You can't use the software !
Minors should study hard , Go to a good University , Serve the motherland .

Running results 2:

Please enter your age :20
You are an adult , You can use the software .
Precious time , Please don't waste too much time on the software .
The software is in use …

sys Modular exit() Function is used to exit the program .

【 example 3】 Judge whether a person's figure is reasonable :


1. height = float(input(" Enter the height ( rice ):"))
2. weight = float(input(" Enter the weight ( kg ):"))
3. bmi = weight / (height * height) # Calculation BMI Index
5. if bmi<18.5:
6. print("BMI Index is :"+str(bmi))
7. print(" Underweight ")
8. elif bmi>=18.5 and bmi<24.9:
9. print("BMI Index is :"+str(bmi))
10. print(" normal range , Pay attention to keep ")
11. elif bmi>=24.9 and bmi<29.9:
12. print("BMI Index is :"+str(bmi))
13. print(" Overweight ")
14. else:
15. print("BMI Index is :"+str(bmi))
16. print(" obesity ")

Running results :

Enter the height ( rice ):1.7
Enter the weight ( kg ):70
BMI Index is :24.221453287197235
normal range , Pay attention to keep

It's important to note that ,Python Is a very unique programming language , It identifies code blocks by indenting , Lines of code with the same indentation belong to the same block of code , So you can't just indent , This can easily lead to grammatical errors . Last , If you don't have a lot of time , And want to quickly python Improve , The most important thing is not afraid of hardship , I suggest you can put up a letter ( Homophone ):276 3177 065 , That's really good , A lot of people are making rapid progress , I need you not to be afraid of hardship ! You can take a look at it ~, Including a copy compiled by Xiaobian 2022 Abreast of the times Python Information and 0 Introduction to Basics , Welcome to junior and advanced students . In not busy time I will give you the solution

In other languages ( Such as C Language 、[C++]、[Java] etc. ), The selection structure also includes switch sentence , Multiple choices can also be achieved , But in Python There is no switch sentence , So when it comes to multiple choices , Only use if else Branch statement .

if else How to judge whether the expression is true

It said ,if and elif hinder “ expression ” It's very free form , As long as the expression has a result , Whatever the type of result ,Python It can be judged that it is “ really ” still “ false ”.

Boolean type (bool) There are only two values , Namely True and False,Python Will be able to True treat as “ really ”, hold False treat as “ false ”.

For numbers ,Python Will be able to 0 and 0.0 treat as “ false ”, Think of other values as “ really ”.

For other types , When the object is empty or is None when ,Python They will be treated as “ false ”, Other situations are treated as true . such as , The following expressions are not true :

“”  # An empty string
[ ]  # An empty list
( )  # An empty tuple
{ }  # An empty dictionary
None  # Null value

【 example 】if elif Judge various types of expressions :


1. b = False
2. if b:
3. print('b yes True')
4. else:
5. print('b yes False')
7. n = 0
8. if n:
9. print('n It's not zero ')
10. else:
11. print('n It's zero ')
13. s = ""
14. if s:
15. print('s Not an empty string ')
16. else:
17. print('s Is an empty string ')
19. l = []
20. if l:
21. print('l It's not an empty list ')
22. else:
23. print('l It's an empty list ')
25. d = {}
26. if d:
27. print('d It's not an empty dictionary ')
28. else:
29. print('d It's an empty dictionary ')
31. def func():
32. print(" Function called ")
34. if func():
35. print('func() The return value is not empty ')
36. else:
37. print('func() The return value is null ')

Running results :

b yes False
n It's zero
s Is an empty string
l It's an empty list
d It's an empty dictionary
Function called
func() The return value is null

explain : For no return Function of statement , The return value is null , That is to say None.


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved