I encountered a very basic problem today, and it turned out to be a long, long time ..... I'll write a blog about it.
Originally two different strings, in the if of the conditional judgment is determined to be True, the following is the error code.
test_str = 'happy' if test_str == 'good' or 'happy': #This if-judgement is always True, wrong way to write it print('aa') else: print('bbbb')
This is the correct code.
test_str = 'happy' if test_str == 'good' or test_str == 'happy': print('aa') else: print('bbbb')
Additional knowledge: python basics (if judgment conditional statements, comparison, boolean operators)
1. Conditions and conditional statements
In the program as written, statements are executed line by line. Now take it a step further and let the program choose whether or not to execute a particular block of statements.
1 ) The Usefulness of Boolean Values
Truth values, also known as Boolean values, are named after George Boole, who made great contributions to truth values.
When used as a Boolean expression (e.g., as a condition in an if statement), any of the following values will be treated as false by the interpreter:
False None 0 "" () [] {}
In other words, the standard values False and None, the value 0 for various types (including floats, complex numbers, etc.), empty sequences (e.g., empty strings, empty tuples, and empty lists), and empty mappings (e.g., empty dictionaries) are treated as false, while various other values are treated as true, including the special value True.
As Python veteran Laura Creighton points out, the difference is akin to the difference between "something" and "nothing" rather than the difference between true and false.
This means that any Python value can be interpreted as true. At first glance this is a bit confusing, but also very useful. While there are a large number of truth values to choose from, the standard truth values are True and False. in some languages (such as C and versions of Python prior to 2.3), the standard truth values are 0 (for false) and 1 (for true). In reality, True and False are just aliases for 0 and 1, which look different but serve the same purpose.
>>> True True >>> False False >>> True == 1 True >>> False == 0 True >>> True + False + 42 43
So if you see an expression that returns 1 or 0 (probably written using an older version of Python), you know that this actually means True or False.
The boolean values True and False belong to the type bool, which, like list, str and tuple, can be used to convert other values.
>>> bool('I think, therefore I am') True >>> bool(42) True >>> bool('') False >>> bool(0) False
Given that any value can be used as a boolean you hardly need to do the conversion explicitly (Pthon does it automatically)
While [] and "" are both false (i.e. bool([]) == bool("") == False), they are not equal (i.e. [] ! = "").
The same is true for various other objects that are false (a more obvious example is () ! = False).
2) Conditional execution and if statements
Truth values can be merged, so let's first see what truth values can be used for. Try running the following script:
name = input('What is your name? ') if ('Gumby'): print('Hello, Mr. Gumby')
This is the if statement, which allows you to execute code conditionally. This means that if the condition (the expression between the if and the colon) is true as defined earlier, the subsequent block of code (in this case a print statement) is executed; if the condition is false, it is not.
3) else clause
In the example in the previous section, if you entered a name ending in Gumby, the method would return True, causing the subsequent block of code to execute - printing the greeting. If you wish, you can add an alternative by using the else clause (so called because else is not a stand-alone statement, but part of an if statement).
name = input('What is your name?') if ('Gumby'): print('Hello, Mr. Gumby') else: print('Hello, stranger')
Here, if the first code block is not executed (because the condition is false), it will go to the second code block.
Another "relative" of the if statement is the conditional expression - the Python version of the C trinomial operator. The following expression uses if and else to determine its value:
status = "friend" if ("Gumby") else "stranger"
If the condition (immediately following the if) is true, the result of the expression is the first value supplied (in this case "friend"), otherwise the second value (in this case "stranger").
4) The elif clause
To check more than one condition, use elif. elif is short for else if, and consists of a combination of an if clause and an else clause, that is, an else clause containing a condition.
num = int(input('Enter a number: ')) ifnum > 0: print('The number is positive') elifnum < 0: print('The number is negative') else: print('The number is zero')
5) Code block nesting
You can place if statements in other if statement blocks as follows:
name = input('What is your name? ') if ('Gumby'): if ('Mr.'): print('Hello, Mr. Gumby') elif ('Mrs.'): print('Hello, Mrs. Gumby') else: print('Hello, Gumby') else: print('Hello, stranger')
Here, if the name ends in Gumby, the beginning of the name is checked at the same time, which is done using a separate if statement in the first code block. Note that elif is also used here. the last branch (the else clause) does not specify a condition - if no other branch is selected, the last one is selected. Both else clauses can be omitted if desired. If the inner else clause is omitted, names that do not begin with Mr. or Mrs. are ignored (assuming the name is Gumby). If the outer else clause is omitted, strangers will be ignored.
6) More complex conditions
1. Comparison operators
Probably the most basic operators in conditional expressions are comparison operators, which are used to perform comparisons.
Theoretically, operators such as < and <= can be used to compare the relative sizes of any two objects x and y and obtain a truth value, but such comparisons only make sense when x and y are of the same or similar type (e.g., two integers or an integer and a floating-point number).
Adding an integer to a string is meaningless, as is checking to see if an integer is less than a string.
Like assignment, Python supports chained comparisons: multiple comparison operators can be used at the same time, e.g. 0 < age < 100. Some comparison operators require special attention
equality operator
To determine whether two objects are equal, use the comparison operator, represented by two equal signs (==).
>>> "foo" == "foo" True >>> "foo" == "bar" False
Two equal signs? Why not use one equals sign like in math? But let's try one equals sign here.
>>> "foo" = "foo"
SyntaxError: can't assign to literal
An equals sign is an assignment operator, used to modify values, which you don't want to do when making comparisons.
is: same operator
This operator is interesting in that it appears to do the same thing as ==, but it doesn't really.
>>> x = y = [1, 2, 3] >>> z = [1, 2, 3] >>> x == y True >>> x == z True >>> x is y True >>> x is z False
In the first few examples, nothing can be seen to be wrong, but the last example has a strange result: x and z are equal, but x is z results in False. why is this so? Because is checks whether two objects are the same (not equal). The variables x and y point to the same list, and z points to another list (which contains the same values and the same order in which those values are listed as the previous list). The two lists are equal, but not the same object. Does this seem implausible? See the following example:
>>> x = [1, 2, 3] >>> y = [2, 4] >>> x is not y True >>> del x[2] >>> y[1] = 1 >>> ()
In this example, I first created two different lists, x and y. As you can see, x is not y (as opposed to x is y) results in True. Next, I modified the two lists slightly so that now they are equal but still two different lists.
>>> x == y True >>> x is y False
Obviously, the two lists are equal but not identical.
In short, == is used to check if two objects are equal, while is is used to check if two objects are the same (are the same object).
Do not use is for immutable primitive values such as numbers and strings. Given the way Python handles these objects internally, the results of doing so are unpredictable.
in: membership operator
Like other comparison operators, it can be used in conditional expressions.
name = input('What is your name?') if 's' in name: print('Your name contains the letter "s".') else: print('Your name does not contain the letter "s".')
Comparison of strings and sequences
Strings are compared based on the alphabetical order of the characters.
>>> "alpha" < "beta"
True
Although based on an alphabetical order, the letters are all Unicode characters and they are arranged by code points.
In fact, the characters are ordered according to their sequential value. To learn the sequential value of the letters, use the ord function, which is the opposite of the chr function.
This approach is both reasonable and consistent, but it may be the opposite of how you want to sort. For example, when capital letters are involved, the ordering may be different from what you want.
>>> "a" < "B"
False
One trick is to ignore case. The string method lower can be used for this purpose, as shown below:
>>> "a".lower() < "B".lower() True >>> 'FnOrD'.lower() == 'Fnord'.lower() True
Other sequences are compared in the same way, but these sequences may contain elements that are not characters, but values of other types.
>>> [1, 2] < [2, 1]
True
If the elements of the sequence are other sequences, these will be compared according to the same rules.
>>> [2, [1, 4]] < [2, [1, 5]]
True
2. Boolean operators
Up to this point, you've seen a lot of expressions that return true values (in fact, all of them return true values, given that all values can be interpreted as true), but you may need to check more than one condition. For example, suppose you want to write a program that reads a number and checks to see if the number lies in the range 1 to 10, inclusive. To do this, do something like the following:
number = int(input('Enter a number between 1 and 10: ')) if number <= 10: if number >= 1: print('Great!') else: print('Wrong!') else: print('Wrong!')
This works, but it's a bit clunky because print('Wrong!') is entered twice. Duplication of effort is not a good thing, so what to do? It's simple.
number = int(input('Enter a number between 1 and 10: ')) if number <= 10 and number >= 1: print('Great!') else: print('Wrong!')
This example can be further simplified by using chain comparisons 1 <= number <= 10.
The operator and is a boolean operator. It accepts two truth values and returns true if both values are true, otherwise it returns false. There are two other Boolean operators: or and not, and by using these three operators, you can combine truth values in any way you want.
if ((cash > price) or customer_has_good_credit) and not out_of_stock:
give_goods()
Short-circuit logic and conditional expressions
Boolean operators have an interesting feature: they only do the necessary calculations. For example, the expression x and y is true only if both x and y are true. So if x is false, the expression will immediately return false, without caring about y. In fact, the expression will return x if x is false, and y otherwise. This behavior is called short-circuiting logic (or delayed evaluation): Boolean operators are often called logical operators, and in some cases will "bypass" the second value. The same is true for the operator or. In the expression x or y, if x is true, x is returned, otherwise y. Note that this means that code following a Boolean operator, such as a function call, may not be executed at all. Code like the following takes advantage of this behavior:
name = input('Please enter your name: ') or '<unknown>'
If no name is entered, the result of the above or expression will be '<unknown>'. In many cases, it is preferable to use conditional expressions rather than short-circuit tricks like this.
Above this python unequal two strings of if condition judgment for True details is all that I share with you, I hope to give you a reference, and I hope you support me more.