Python if application details

Source: Internet
Author: User

Many times Python if applications are used in Python programming. This problem makes many people do not know how to solve it. Next, let's take a look at the related Python if application solutions. I hope these codes will help you.

Python uses the if, elif, and else keywords for condition judgment. The only difference from C # Is that elif replaces else if with elif, with less words, and the other words are the same. In addition, do not forget to add the following after the if statement: Oh!

If a Process Control Branch does not do anything, remember to write a pass statement. Otherwise, Python will report an error. For example:

If 0: 2 pass # neural network! What is this example?

There is no switch statement in Python. You can use the if... elif... else statement to do the same job. If you think it is cumbersome, you can try the dict implementation method. The following is an example, which compares the two implementation methods.

 
 
  1. # Class C # pseudo code, which selects different program behaviors based on different input parameters
  2. Switch (x ):
  3. Ase "1 ":
  4. Print 'one'; break;
  5. Case "2 ":
  6. Print 'two'; break;
  7. Default:
  8. Print 'nothing! '# Use if instead
  9. If x = '1 ':
  10. Print 'one'
  11. Elif x = '2 ':
  12. Print 'two'
  13. Else: print 'nothing! '# Use dict
  14. Numtrans = {1: 'one', 2: 'two ',...}
  15. Try:
  16. Print numtrans [x]
  17. Failed t KeyError:
  18. Rint 'nothing! '# You can also use method functions in the Branch)
  19. Def print_one ():
  20. Print 'one'
  21. Def print_two ():
  22. Print 'two'
  23. Numtrans = {1: print_one, 2: print_two ,}
  24. Try:
  25. Numtrans [x] () # note that the method can be executed by name + parentheses. This is actually awesome.
  26. Counter t KeyError: 42 print 'nothing! '

The above is a detailed introduction to the Python if application, and I hope you will get some benefits.
 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.