current position：Home>Python from 0 to 1 (day 15) - Python conditional judgment 2
Python from 0 to 1 (day 15) - Python conditional judgment 2
2022-02-01 04:23:10 【My family】
This is my participation 11 The fourth of the yuegengwen challenge 20 God , Check out the activity details ：2021 One last more challenge
Two way judgment ,if...else...
stay Python The world , We can use if Two way judgment form ：
if…else… To achieve this action ： When the number of remaining wallets is less than 1 when , We need to send blessings to those who rob red envelopes , Late. , But I wish you all the best !!!
below , Please run the following code directly , See how the program recognizes ：
# Number of remaining red envelopes redpacketnumber=0 # Conditions ： If the number of remaining red envelopes is greater than or equal to 1 if redpacketnumber >=1: # result ： Show ‘ Successfully grabbed the red envelope ’ Result print(' Successfully grabbed the red envelope ') else: # result : Show ' Late. , But I wish you all the best !!!' Result print(' Late. , But I wish you all the best !!!') Copy code
In fact, life is the same , Many things are not either or , When the conditions are not met , What are we going to do .
Python It's very sweet , Let's borrow if...else sentence , Let the yard farmer have another choice ---[ If ... Just , otherwise ... Just ]
stay if...else In a conditional statement ,if and else Hold each other together , Form two different code blocks . And other conditions are mutually exclusive —— If not satisfied if Conditions , Is executed else Other conditions .
If we use the example of robbing red envelopes above to explain ,if The definition is the number of remaining red envelopes >=1, and else The definition is the number of remaining red envelopes <1.
And because of the assignment 【
redpacketnumber =0】, Not satisfied 【
if redpacketnumber >=1:】 This condition , So we can't execute 【
print(' Successfully grabbed the red envelope ')】 The order of .
Only the second way else: Way —— perform
print(' Late. , I wish you all the best !!!') Result .
below , Let's do a problem to consolidate if...else... Knowledge points of : Grab the red envelope , We can go to dinner , But what to eat still has to be decided according to the number of red envelopes , If we grab more red envelopes than 50 element , We can have a ton of meat , If not more than 50 element , We can only be vegetarian .
# First assign a value to the amount of the red envelope , Suppose you get 38 element money=38 # If the red envelope exceeds 50 Under the condition of , Just ...( A colon is required after the condition ) if money>50: # Just print the results : Take a big bite of meat , Drink heavily print(' Take a big bite of meat , Drink heavily ') # If the red envelope does not exceed 50, Just ...（else No indent before condition , A colon is required after the condition ） else: # Just print : Vegetarianism , Health preservation is the last word print(' Vegetarian attention , Health preservation is the last word ') Copy code
About if...else... That's all for you , Let's summarize if…else… Knowledge points of statements .
In the practice of eating above , We will find that , It's not just two sides , There may be a third side , Actually 38 Yuan, we can also go with some meat dishes , Meat and vegetable collocation , More nutrition , Healthier .
that , There are three in the scene if Python How to achieve it ？
Multidirectional judgment ：if…elif…else…
In the above scenario , In judging 3 Or 3 More than one condition , We need to use Python Multidirectional judgment command in ：if…elif…else….
These three together constitute the command logic relationship of multi-directional judgment ： If if The condition of is not satisfied , It depends on the order of satisfaction elif Conditions , If not satisfied elif Conditions , Is executed else The order of .
also , When the condition of judgment exceeds 3 Time , Multiple conditions in the middle can be used elif.
that , How to write this code ？ Let's feel it in the code elif The logic of
# First assign a value to the amount of the red envelope , Suppose you get 38 element money=38 # If the red envelope exceeds 50 Under the condition of , Just ...( A colon is required after the condition ) if money > 50: # Just print the results : Take a big bite of meat , Drink heavily print(' Take a big bite of meat , Drink heavily ') # If the red envelope exceeds 35, Not more than 50 elif 50 >= money > 35: print(' Meat and vegetable collocation , More nutrition , Healthier ') # If the red envelope does not exceed 50, Just ...（else No indent before condition , A colon is required after the condition ） else: # Just print : Vegetarianism , Health preservation is the last word print(' Vegetarian attention , Health preservation is the last word ') Copy code
Pass above if and else The accumulation of , Multidirectional judgment elif Is it easy to understand the logic of ?
First , The assignment of the first line , I'll try it one by one from top to bottom , See what conditions you meet , If you are satisfied, don't go down , If you are not satisfied, continue to try , Until you get the results .
secondly ,elif The operation of is essentially the same as else equally , Has the meaning of other conditions , therefore elif You can not answer else.
Like the code above ,money=38 Will be on the following if elif else Scan conditions one by one , See which one you satisfy , Just execute the command under which conditions .
Obviously , The second condition elif 50 >= money > 35 Just like money=5 Match the premise of , therefore , perform elif The following command :
print(' Meat and vegetable collocation , More nutrition , Healthier ')
below , Let's summarize elif Knowledge points of ：
author[My family],Please bring the original link to reprint, thank you.
The sidebar is recommended
- Django paging (II)
- Concurrent. For Python concurrent programming Futures or multiprocessing?
- Programmers over the age of 25 can't know a few Chinese herbal medicines. Python crawler lessons 9-9
- Python crawler from introduction to pit full series of tutorials (detailed tutorial + various practical combat)
- The second bullet of class in Python
- Python object oriented programming 03: class inheritance and its derived terms
- How IOS developers learn Python Programming 13 - function 4
- Python crawler from introduction to mastery (VI) form and crawler login
- Python crawler from entry to mastery (V) challenges of dynamic web pages
- Deeply understand pandas to read excel, TXT, CSV files and other commands
guess what you like
Daily python, Chapter 18, class
"I just want to collect some plain photos in Python for machine learning," he said. "I believe you a ghost!"
Python implements filtering emoticons in text
When winter comes, python chooses a coat with temperament for mom! Otherwise, there's really no way to start!
Python crawler - get fund change information
Highlight actor using Python VTK
Python crawler actual combat: crawling southern weekend news articles
leetcode 406. Queue Reconstruction by Height（python）
leetcode 1043. Partition Array for Maximum Sum （python）
- Python * * packaging and unpacking details
- Python realizes weather query function
- Python from 0 to 1 (day 12) - Python data application 2 (STR function)
- Python from 0 to 1 (day 13) - Python data application 3
- Numpy common operations of Python data analysis series Chapter 8
- How to implement mockserver [Python version]
- Van * Python! Write an article and publish the script on multiple platforms
- Python data analysis - file reading
- Python data De duplication and missing value processing
- Python office automation - play with browser
- Python series tutorial 127 -- Reference vs copy
- Control flow in Python: break and continue
- Teach you how to extract tables in PDF with Python
- leetcode 889. Construct Binary Tree from Preorder and Postorder Traversal（python）
- leetcode 1338. Reduce Array Size to The Half（python）
- Object oriented and exception handling in Python
- How to configure load balancing for Django service
- How to embed Python in go
- Python Matplotlib drawing graphics
- Python object-oriented programming 05: concluding summary of classes and objects
- Python from 0 to 1 (day 14) - Python conditional judgment 1
- Several very interesting modules in Python
- How IOS developers learn Python Programming 15 - object oriented programming 1
- Daily python, Chapter 20, exception handling
- Understand the basis of Python collaboration in a few minutes
- [centos7] how to install and use Python under Linux
- leetcode 1130. Minimum Cost Tree From Leaf Values（python）
- leetcode 1433. Check If a String Can Break Another String（python）
- Python Matplotlib drawing 3D graphics
- Talk about deep and shallow copying in Python
- Python crawler series - network requests
- Python thread 01 understanding thread
- Analysis of earthquake distribution in the past 10 years with Python~
- You need to master these before learning Python crawlers
- After the old friend (R & D post) was laid off, I wanted to join the snack bar. I collected some data in Python. It's more or less a intention
- Python uses redis
- Python crawler - ETF fund acquisition
- Detailed tutorial on Python operation Tencent object storage (COS)
- [Python] comparison of list, tuple, array and bidirectional queue methods
- Go Python 3 usage and pit Prevention Guide