Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use conditional judgment statement in python

2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

This article mainly shows you "how to use conditional judgment sentences in python". The content is simple and clear. I hope it can help you solve your doubts. Let me lead you to study and learn this article "how to use conditional judgment sentences in python".

1. Avoid multi-layer branch nesting

Python uses indentation instead of {}. If multiple if are nested, it can be called "nested if hell".

The following code translates the original conditional branch directly, resulting in poor readability and maintenance of the code.

Def buy_fruit (nerd, store): "go to the fruit store to buy apples-first see if the store is open-if there are any apples, buy one-if there is not enough money Just go home and withdraw money. "" if store.is_open (): if store.has_stocks ("apple"): if nerd.can_afford (store.price ("apple", amount=1)): nerd.buy (store, "apple") Amount=1) return else: nerd.go_home_and_get_money () return buy_fruit (nerd, store) else: raise MadAtNoFruit ("no apple in store!") Else: raise MadAtNoFruit ("store is closed!")

We optimize this code by "ending ahead of time" by getting rid of it:

Def buy_fruit (nerd, store): if not store.is_open (): raise MadAtNoFruit ("store is closed!") If not store.has_stocks ("apple"): raise MadAtNoFruit ("no apple in store!") If nerd.can_afford (store.price ("apple", amount=1): nerd.buy (store, "apple", amount=1) return else: nerd.go_home_and_get_money () return buy_fruit (nerd, store)

"early end": refers to the use of statements such as return or raise within the function to end the function in advance within the branch.

Using reverse thinking, when the branching condition is not met, we directly end this code, which makes it easier to read.

two。 Encapsulate overly complex logical judgments

If there are too many judgment conditions and | not | or in the conditional branch, you can encapsulate such a part.

If person.is_student and person.age > 20 and person.is_male: pass

In this way, the encapsulated part is more explainable and easier to understand.

The most important thing is to solve the problem that occurs many times in the same code.

If person.identity () and person.gender (): pass3. Duplicate code under different branches

The following code is hard to tell the difference intuitively:

If person.is_student (): record_imformation (name = person.name, age = person.name, address = person.address, student_number = 10011, recorded = now (),) else: update_information (name = person.name, age = person.name, address = person.address, updated = now ())

Focus on these repetitive blocks of code generated by branches and simplify them through transformation.

If person.is_student (): imformation_func = record_imformation extra_args = {'student_number': 10011,' recorded': now ()} else: imformation_func = update_information extra_args = {'updated': now ()} information_func (name = person.name, age = person.name, address = person.address, * * extra_args) 4. Rational use of ternary expressions

Code is usually more readable using normal if / else statements.

For ternary expressions, you can only deal with simple logical branches.

Language = "python" if you.favor ("dynamic") else "golang" 5. Common skills 5.1 de Morgan's Law

For the following code, it is difficult to get to a logical relationship in the first place.

# if the user is not logged in or does not use chrome, refuse to provide service if not user.has_logged_in or not user.is_from_chrome: return "our service is only available for chrome logged in user"

And use de Morgan's law.

Not An or not B = not (An and B), the code is much easier to read.

If not (user.has_logged_in and user.is_from_chrome): return "our service is only available for chrome logged in user" 5.2 Magic methods for custom classes

Python provides magic methods with multiple custom classes, which we can use to make our code more pythonic.

The following code uses the len () function.

Class UserCollection (object): def _ init__ (self, users): self._users = usersusers = UserCollection ([piglei, raymond]) if len (users._users) > 0: print ("There's some users in collection!")

Branching conditions become easier by customizing magic methods for classes.

And you can control the return value of the magic method yourself.

Class UserCollection: def _ init__ (self, users): self._users = users def _ len__ (self): return len (self._users) users = UserCollection ([piglei, raymond]) # once the _ _ len__ method is defined, the UserCollection object itself can be used for Boolean judgment if users: print ("There's some users in collection!") 5.3 uses all () / any () in conditional judgment

All (x): returns True if all objects in x are true, otherwise False

Any (x): returns True as long as one of the objects in x is true, otherwise False

Def all_numbers_gt_10 (numbers): "" returns True only if all numbers in the sequence are greater than 10:00 "" if not numbers: return False for n in numbers: if n 10 for n in numbers) 5.4.Use the else branch def do_stuff (): first_thing_successed = False try: # in try/while/for. First_thing_successed = True except Exception as e: #... Return # only if first_thing completes successfully, do the second thing if first_thing_successed: return do_the_second_thing ()

In fact, we can achieve the same effect in a simpler way:

Def do_stuff (): try: #... Except Exception as e: #... Return else: return do_the_second_thing ()

Add the else branch after the statement block of try.

Similar for / while supports else branches.

6. Common traps 6.1 are worth comparing with None

In python, there is a fundamental difference between the two comparison methods of = = and is.

=: only compare whether the values of the two are consistent

Is: compare whether the two point to the same address in memory.

But None is a singleton object in python. If you want to judge whether a variable is None or not, you need to use is. Only is strictly indicates whether a variable is None.

Operational priority of 5.2and and or

The priority of and is higher than or

Even if the priority of execution is as consistent as we want, additional parentheses should be used to make the code clearer.

(True or False) and False # FalseTrue or False and False # True

In addition:

C and an or b doesn't always give the right results. This expression works only when the Boolean values of an and b are true because of the short-circuit nature of logical operations.

The above is all the contents of the article "how to use conditional judgment sentences in python". Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more knowledge, welcome to follow the industry information channel!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report