This question already has answers here:
How do "and" and "or" act with non-boolean values?
(8 answers)
Closed 6 months ago.
I'm a little confused with the results I'm getting with the logical operators in Python. I'm a beginner and studying with the use of a few books, but they don't explain in as much detail as I'd like.
here is my own code:
five = 5
two = 2
print five and two
>> 2
It seems to be just outputting the two variable.
five = 5
two = 2
zero = 0
print five and two and zero
So, I added another variable integer. Then I printed and got the following output:
>> 0
What is going on with Python in the background? Why isn't the output something like 7 or 5, 2.
Python Boolean operators return the last value evaluated, not True/False. The docs have a good explanation of this:
The expression x and y first evaluates x; if x is false, its value is returned; otherwise, y is evaluated and the resulting value is returned.
As a bit of a side note: (i don't have enough rep for a comment) The AND operator is not needed for printing multiple variables. You can simply separate variable names with commas such as print five, two instead of print five AND two. You can also use escapes to add variables to a print line such as print "the var five is equal to: %s" %five. More on that here: http://docs.python.org/2/library/re.html#simulating-scanf
Like others have said AND is a logical operator and used to string together multiple conditions, such as
if (five == 5) AND (two == 2):
print five, two
Boolean And operators will return the first value 5 if the expression evaluated is false, and the second value 2 if the expression evaluated is true. Because 5 and 2 are both real, non-false, and non-null values, the expression is evaluated to true.
If you wanted to print both variables you could concatenate them to a String and print that.
five = 5
two = 2
print five + " and " + two
Or to print their sum you could use
print five + two
This document explains how to use the logical Boolean operators.
This AND in Python is an equivalent of the && in Java for instance. This doesn't mean the and in the English language. The AND is a logical operator. Assume five holds 5 and two holds 2. From Python documentation: The expression x and y first evaluates x; if x is false, its value is returned; otherwise, y is evaluated and the resulting value is returned. Basically, it evaluates the last integer in your case which is true.
if (five and two):
... print "True"
... else:
... print "False"
The AND is a logical operator, to test the logic for a specific case, not an arithmetic operator. If you want to get results like 7 for five and two, you should rather use "+" which means adding two integers. See below:
>>> five = 5
>>> two = 2
>>> print five + two
7
Try 0 and 9.
The result is 0 because the value of 0 is false. The operand on the left of the and operator is False so the whole expression is False and returns 0
In Python any non-zero integer value is true; zero is false.
The OP’s values are both non-zero.
The AND operator tests from left to right,
with and, if all values are True, returns the last evaluated value.
If any value is false, returns the first one.
Since both are non-zero, both are true, so the last value is returned
To convert the integer variable to a string , add str in front of each variable
five = 5
two = 2
print(str(five) + " and " + str(two))
Related
Trying to understand how AND statement works inside abs(numbers) function.
Calling print(abs(21-22 and 9-4 and 11-8))
This would always give me whatever the last expression is. In this case it calculates 11-8, so it prints 3.
Why other expressions are not in the output and no error as well?
The fact that the expression is inside an abs call doesn't change the way that it's interpreted:
>>> 21-22 and 9-4 and 11-8
3
which is of course the same as:
>>> -1 and 5 and 3
3
An and evaluates the "truthiness" of each operand. If either of them is "falsey", that one is returned; otherwise the last one is returned.
All int values except 0 are "truthy", so the only time you'll get something other than the last value from an and of ints is if one of them is zero:
>>> -1 and 0 and 3
0
and is a logical operator, it will return True if both the operands of the operator are true. I believe the comma does what you expected to do in this case:
print(abs(21-22),abs(9-4),abs(11-8))
I recently encountered an example of an if-else conditional statement and could not understand the rationale behind its output. The following are the statements:
if 0:
1
else:
2
Output: 2
I tried different integers in 0's place, and received 1 each time. Is this because the zero in the if condition represents False? But then why do integers other than 1 still satisfy the if condition?
Thanks!
Edit: Thank you for all your answers. I now understand that any integer except 0 in the 'if' statement will make the statement True by default, resulting in an output of 1, in this case.
Python will always attempt to determine the "truthiness" of a given value used in a boolean context. In Python any numerical value of 0 (or 0.0) is considered false, and string, dictionary, list, or other iterable (or other class that can report its length) is false if it's empty or has length of 0. Also, None and boolean False are considered false.
Other values are considered true.
More details: https://docs.python.org/2.4/lib/truth.html.
In Python, bool is a subtype of int. False has the value 0, while other non-zero integers have the subtype bool with the value True.
To see this for yourself try this: False == 0
And to see the subtypes of int try this: int.__subclasses__()
1 is considered True while 0 is False,just like in binary.
Any non-zero numeric value is evaluated as True in a conditional statement.
bool type is just a subtype of int in Python, with 1 == True and 0 == False.
The following code will output infinite lines of "test".
foo = 5
while foo:
print("bar")
The other day I came across an answer here about digit sums. This was the code shown in the answer:
def digit_sum(t):
s = 0
while t:
s += t % 10
t //= 10
return s
The part I'm focusing on is the "while t:" part. How and why does this work?
The while condition tests for truth. Any non-zero numeric value is considered true. See the Truth Value Testing section in the Python documentation:
Any object can be tested for truth value, for use in an if or while
condition or as operand of the Boolean operations below. The following
values are considered false:
None
False
zero of any numeric type, for example, 0, 0L, 0.0, 0j.
any empty sequence, for example, '', (), [].
any empty mapping, for example, {}.
instances of user-defined classes, if the class defines a
__nonzero__() or __len__() method, when that method returns the integer zero or bool value False.
All other values are considered true — so objects of many types are
always true.
Bold emphasis mine.
In your sample while loop, t trends to 0 (integer division by 10), so eventually while t: ends because t is considered false.
You already got useful answers, but I just wanted to answer your question in a way that can be easily understood by someone who is a beginner in Python.
You could rewrite your code as:
def digit_sum(t):
s = 0
while t!=0:
s += t % 10
t = t//10
return s
'while t' is equivalent to 'while t!=0', meaning that the loop will end when t is equal to 0.
In your for loop, 't //= 10' is equivalent to 't = t // 10' ('//' is a floor division operator and returns an integer). So the value of t becomes smaller each time the loop is executed, until it eventually reaches the value of 0. At this point, the 'while t' condition is False and the loop ends.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I know that the program convert Decimal to Binary,in fact I'm just a beginner in programming and python is my starting language.
answering these questions will help me a lot.
def bin(i):
s = "" # what do we mean by s="" ? does it mean s=0?
while i: # where is the condition ?
if i & 1: # what is the equivalent for '&'? when I put 'and' instead of '&' I get differnt results?why?
s = "1" + s # ?
else:
s = "0" + s
i = i//2 # why?
return s
the problem is that I want to undestand what happen between the input and the output?
one more thing can we extend this code to floating numbers how ?
Let me try to answer your questions one at a time; you should then be able to piece them all together:
s = "" # what do we mean by s="" ? does it mean s=0?
s is now an empty string. You could add other strings to it, to concatenate them. Indeed, this is what is done later on, in the line s = "1" + s. Take a look:
In [21]: "1" + ""
Out[21]: '1'
In [22]: "1" + "2"
Out[22]: '12'
In [23]: s = ""
In [24]: "1" + s
Out[24]: '1'
See how string concatenation works?
Next:
while i: # where is the condition ?
Ah! there is a nuance in many programming languages (including python) that an integer whose value is 0 evaluates to a boolean of False, when used in a conditional statement (like if or while). All non-zero values evaluate to True.
Therefore, this while loop is saying while i does not take the value of 0. Note that because of the division on i later on, i will never take on a negative value, and this loop therefore terminates.
Next:
if i & 1: # what is the equivalent for '&'? when I put 'and' instead of '&' I get differnt results?why?
i&1 is a bit-wise AND operator. Suppose i has the value of 5. Then, the binary representation of i is 101. the binary representation of 1 is simply 1, or 001 (since we are comparing it with 101). So now, we perform the bit-wise AND, which basically compares each pair of corresponding bits, outputting 1 if they are both 1s (0 otherwise). The result of comparing 101 and 001 thusly, is 001, which translates to a value of 1. All this means is that when you divide i by 2, you get a remainder of 1. Since the only possibilities for this are 1 (which evaluates to True in the if-statement) or 0 (which evaluates to False in the if-statement), it lends itself to be very easily used in such a dichotomous fashion (to add either a "0" or a "1" to s)
Next:
i = i//2
This is a truncated division with an integer casting. Watch:
In [27]: i = 4
In [28]: i/2
Out[28]: 2.0
In [29]: i//2
Out[29]: 2
In [30]: i = 5
In [31]: i/2
Out[31]: 2.5
In [32]: i//2
Out[32]: 2
Get it?
This question already has answers here:
Does Python support short-circuiting?
(3 answers)
How do "and" and "or" act with non-boolean values?
(8 answers)
Closed 9 years ago.
When I test the difference between and and or, I meet this problem. Could you please help me understand it?
This behavior is a weird quirk that comes out of three different features of python code. Non-zeros values are true, logical operation evaluation, and short-circuiting. I'll explain these features below:
Non-Zero Values are True
The first thing you have to know in evaluating these expressions is that they are logical operators. They are designed to work with true or false values:
true and true = true
true and false = false
false and true = false
false and false = false
true or true = true
true or false = true
false or true = true
false or false = false
However, python (and many languages) allow you to put any value in. So long as they are non-zero they are considered true. So:
4 and 5 = true
4 and 0 = false
This is normal so far. Most languages have this.
Logical Operation Evaluation
Here Python does something a little unique. Instead of returning true or false, it actually returns the value of the last item it checked in the statement. So:
4 and 5 = 5 (which will be evaluated as true)
To fully understand which value will actually get returned you have to also understand:
Short-Circuiting
When evaluating these logical operators, the compiler can often stop early. Take the example:
3 or 4
We know that the statement will return true, but which value will it return? To figure this out you have to understand which value will be the last one looked at. The system will look at 3, and realize that the statement is true. It doesn't matter what the second value is, 3 or anything is true. So the value returned is 3 because it is the last value checked.
However, if we use and:
3 and 4
Once we look at 3, we still need to check that the second value is true. It could makes a difference. So the second value is evaluated. If it is true, it returns the last value looked at, in this case 4.
In Conclusion
You just have to think about which value the interpreter can stop on.
3 or 4 = 3 // because we can stop at 3
3 and 4 = 4 // because we have to check the 4
0 or 3 = 3 // because we needed to check the 3
Yes, the and operator requires all arguments to be true, and returns the last one checked, which is 5. (If any of the arguments were false, it would return the first false value, since that would be the last one checked in order to verify if all arguments were true.)
The or operator requires only one argument to be true, and returns the last one checked, which is 4, because 4 represents the first true value in the conditional. (If all arguments were false, then the return value would be equal to the last false value, since that would be the last value checked in order to verify if any of the arguments were true.)
true1 and true2 >>>true2
true1 or true2 >>>true1
when runinng true1 and true2, python must check the value returned by every expression is true or not, so it will return the last one.
but when running true1 or true2 , as true1 retrun "true" (in your example, 4 is "true") already, so it is unncessary to continue checking the rest.
I think the way to look at it is at a simpler level, which was designed for optimization.
and requires that both sides be "truthy." It checks the left side. If it is "truthy," it returns the second value without checking what it is.
or requires only one side to be "truthy." It checks the first side. If it is "truthy," it returns it. If not, it returns the second side, again without checking it.
For "4 and 5", because 4 is "truthy," it returns 5.
For "4 or 5", it returns 4 without even looking at 5.
Need proof? Make these functions:
def four():
print 'Evaluating four!'
return 4
def five():
print 'Evaluating five!'
return 5
Now see what gets printed:
>>> four() and five()
Evaluating four!
Evaluating five!
5
and evaluated four(), and since it was true it returned five().
>>> left() or right()
Evaluating left side!
4
or evaluated four() and since it was true, returned four() without even calling five()!