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.
- # Class C # pseudo code, which selects different program behaviors based on different input parameters
- Switch (x ):
- Ase "1 ":
- Print 'one'; break;
- Case "2 ":
- Print 'two'; break;
- Default:
- Print 'nothing! '# Use if instead
- If x = '1 ':
- Print 'one'
- Elif x = '2 ':
- Print 'two'
- Else: print 'nothing! '# Use dict
- Numtrans = {1: 'one', 2: 'two ',...}
- Try:
- Print numtrans [x]
- Failed t KeyError:
- Rint 'nothing! '# You can also use method functions in the Branch)
- Def print_one ():
- Print 'one'
- Def print_two ():
- Print 'two'
- Numtrans = {1: print_one, 2: print_two ,}
- Try:
- Numtrans [x] () # note that the method can be executed by name + parentheses. This is actually awesome.
- 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.