What are the writing methods of Python conditional statements
This article mainly explains "what are the writing methods of Python conditional sentences". Interested friends may wish to have a look. The method introduced in this paper is simple, fast and practical. Next, let the editor take you to learn "what are the ways to write Python conditional sentences"?
0. Original code
This is a very simple piece of code to judge whether a person is an adult by age. Because there are too many lines of code, some people are reluctant to write it, because it does not reflect their years of Python skills.
If age > 18: return "adult" else: return "minor"
Below, I list five variant writing methods of this code, one is better than the other, and it is easier to understand it alone. If you put it in the engineering code, people who have not used these methods will certainly look confused and then inadvertently shout: shit, you can still write like this, and then you have to start swearing: is this the code for people to see? (except for the first one)
1. First kind
Syntax:
If else
Examples
> age1 = 20 > age2 = 17 > msg1 = "mature" if age1 > 18 else "minor" > print msg1 has come of age > msg2 = "mature" if age2 > 18 else "minor" > print msg2 minor >
two。 The second kind
Grammar
And or
Examples
> > msg1 = age1 > 18 and "Adult" or "minor" > > msg2 = "mature" if age2 > 18 else "minor" > print (msg1) has come of age > print (msg2)
3. The third kind
Grammar
("false", "true") [condition]
Examples
> msg1 = ("underage", "underage") [age1 > 18] > print (msg1) underage > msg2 = ("underage", "underage") [age2 > 18] > print (msg2) underage
4. The fourth kind
Grammar
(lambda:, lambda:) [] ()
Examples
> msg1 = (lambda: "minor", lambda: "minor") [age1 > 18] () > print (msg1) has come of age > msg2 = (lambda: "minor", lambda: "minor") [age2 > 18] () > print (msg2) minor
5. The fifth kind
Syntax:
{True:, False:} []
Example:
> msg1 = {True: "adult", False: "minor"} [age1 > 18] > print (msg1) has come of age > msg2 = {True: "adult", False: "minor"} [age2 > 18] > print (msg2) minor
6. The sixth kind
Grammar
(() and (,) or (,)) [0]
Examples
> msg1 = ((age1 > 18) and ("minor",)) [0] > print (msg1) has come of age > msg2 = ((age2 > 18) and ("minor",) or ("minor",) [0] > print (msg2) so far, I believe you have a deeper understanding of "what Python conditional sentences are written". You might as well do it in practice! Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!