true === TRUE and false === FALSEExample 1:This example displays Boolean values ​​in the top and lowercase.
// PHP illustration program
// boolean
// Declare a variable and initialize it
$boolean
= TRUE;
// Show variable value
echo
$boolean
.
""
;
// Declare a variable and initialize it
$boolean
= true;
// Show variable value
echo
$boolean
;
?>
Exit:1 1
Example.This example compares an uppercase and lowercase boolean value.
// PHP illustration program
// boolean
// Declare a variable and initialize it
$var1
= TRUE;
$var2
= true;
// Check that both booleans are the same or not
if
(
$var1
==
$var2
)
echo
"TRUE and true both are same"
;
else
echo
" TRUE and true both are different "
;
// Declare a variable and initialize it
$var1
= FALSE;
$var2
= false;
// Check that both booleans are the same or not
if
(
$var1
==
$var2
)
echo
"FALSE and false both are same"
;
else
echo
" FALSE and false both are different "
;
?>
Exit:TRUE and true both are same FALSE and false both are same
Uppercase logical and lowercase letters in PHP: StackOverflow Questions
Python"s equivalent of && (logical-and) in an if-statement
Question by delete
Here"s my code:
def front_back(a, b):
# +++your code here+++
if len(a) % 2 == 0 && len(b) % 2 == 0:
return a[:(len(a)/2)] + b[:(len(b)/2)] + a[(len(a)/2):] + b[(len(b)/2):]
else:
#todo! Not yet done. :P
return
I"m getting an error in the IF conditional.
What am I doing wrong?
Answer #1:
You would want and
instead of &&
.
Answer #2:
Python uses and
and or
conditionals.
i.e.
if foo == "abc" and bar == "bac" or zoo == "123":
# do something
Answer #3:
I"m getting an error in the IF conditional. What am I doing wrong?
There reason that you get a SyntaxError
is that there is no &&
operator in Python. Likewise ||
and !
are not valid Python operators.
Some of the operators you may know from other languages have a different name in Python.
The logical operators &&
and ||
are actually called and
and or
.
Likewise the logical negation operator !
is called not
.
So you could just write:
if len(a) % 2 == 0 and len(b) % 2 == 0:
or even:
if not (len(a) % 2 or len(b) % 2):
Some additional information (that might come in handy):
I summarized the operator "equivalents" in this table:
+------------------------------+---------------------+
| Operator (other languages) | Operator (Python) |
+==============================+=====================+
| && | and |
+------------------------------+---------------------+
| || | or |
+------------------------------+---------------------+
| ! | not |
+------------------------------+---------------------+
See also Python documentation: 6.11. Boolean operations.
Besides the logical operators Python also has bitwise/binary operators:
+--------------------+--------------------+
| Logical operator | Bitwise operator |
+====================+====================+
| and | & |
+--------------------+--------------------+
| or | | |
+--------------------+--------------------+
There is no bitwise negation in Python (just the bitwise inverse operator ~
- but that is not equivalent to not
).
See also 6.6. Unary arithmetic and bitwise/binary operations and 6.7. Binary arithmetic operations.
The logical operators (like in many other languages) have the advantage that these are short-circuited.
That means if the first operand already defines the result, then the second operator isn"t evaluated at all.
To show this I use a function that simply takes a value, prints it and returns it again. This is handy to see what is actually
evaluated because of the print statements:
>>> def print_and_return(value):
... print(value)
... return value
>>> res = print_and_return(False) and print_and_return(True)
False
As you can see only one print statement is executed, so Python really didn"t even look at the right operand.
This is not the case for the binary operators. Those always evaluate both operands:
>>> res = print_and_return(False) & print_and_return(True);
False
True
But if the first operand isn"t enough then, of course, the second operator is evaluated:
>>> res = print_and_return(True) and print_and_return(False);
True
False
To summarize this here is another Table:
+-----------------+-------------------------+
| Expression | Right side evaluated? |
+=================+=========================+
| `True` and ... | Yes |
+-----------------+-------------------------+
| `False` and ... | No |
+-----------------+-------------------------+
| `True` or ... | No |
+-----------------+-------------------------+
| `False` or ... | Yes |
+-----------------+-------------------------+
The True
and False
represent what bool(left-hand-side)
returns, they don"t have to be True
or False
, they just need to return True
or False
when bool
is called on them (1).
So in Pseudo-Code(!) the and
and or
functions work like these:
def and(expr1, expr2):
left = evaluate(expr1)
if bool(left):
return evaluate(expr2)
else:
return left
def or(expr1, expr2):
left = evaluate(expr1)
if bool(left):
return left
else:
return evaluate(expr2)
Note that this is pseudo-code not Python code. In Python you cannot create functions called and
or or
because these are keywords.
Also you should never use "evaluate" or if bool(...)
.
Customizing the behavior of your own classes
This implicit bool
call can be used to customize how your classes behave with and
, or
and not
.
To show how this can be customized I use this class which again print
s something to track what is happening:
class Test(object):
def __init__(self, value):
self.value = value
def __bool__(self):
print("__bool__ called on {!r}".format(self))
return bool(self.value)
__nonzero__ = __bool__ # Python 2 compatibility
def __repr__(self):
return "{self.__class__.__name__}({self.value})".format(self=self)
So let"s see what happens with that class in combination with these operators:
>>> if Test(True) and Test(False):
... pass
__bool__ called on Test(True)
__bool__ called on Test(False)
>>> if Test(False) or Test(False):
... pass
__bool__ called on Test(False)
__bool__ called on Test(False)
>>> if not Test(True):
... pass
__bool__ called on Test(True)
If you don"t have a __bool__
method then Python also checks if the object has a __len__
method and if it returns a value greater than zero.
That might be useful to know in case you create a sequence container.
See also 4.1. Truth Value Testing.
NumPy arrays and subclasses
Probably a bit beyond the scope of the original question but in case you"re dealing with NumPy arrays or subclasses (like Pandas Series or DataFrames) then the implicit bool
call
will raise the dreaded ValueError
:
>>> import numpy as np
>>> arr = np.array([1,2,3])
>>> bool(arr)
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
>>> arr and arr
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
>>> import pandas as pd
>>> s = pd.Series([1,2,3])
>>> bool(s)
ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
>>> s and s
ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
In these cases you can use the logical and function from NumPy which performs an element-wise and
(or or
):
>>> np.logical_and(np.array([False,False,True,True]), np.array([True, False, True, False]))
array([False, False, True, False])
>>> np.logical_or(np.array([False,False,True,True]), np.array([True, False, True, False]))
array([ True, False, True, True])
If you"re dealing just with boolean arrays you could also use the binary operators with NumPy, these do perform element-wise (but also binary) comparisons:
>>> np.array([False,False,True,True]) & np.array([True, False, True, False])
array([False, False, True, False])
>>> np.array([False,False,True,True]) | np.array([True, False, True, False])
array([ True, False, True, True])
(1)
That the bool
call on the operands has to return True
or False
isn"t completely correct. It"s just the first operand that needs to return a boolean in it"s __bool__
method:
class Test(object):
def __init__(self, value):
self.value = value
def __bool__(self):
return self.value
__nonzero__ = __bool__ # Python 2 compatibility
def __repr__(self):
return "{self.__class__.__name__}({self.value})".format(self=self)
>>> x = Test(10) and Test(10)
TypeError: __bool__ should return bool, returned int
>>> x1 = Test(True) and Test(10)
>>> x2 = Test(False) and Test(10)
That"s because and
actually returns the first operand if the first operand evaluates to False
and if it evaluates to True
then it returns the second operand:
>>> x1
Test(10)
>>> x2
Test(False)
Similarly for or
but just the other way around:
>>> Test(True) or Test(10)
Test(True)
>>> Test(False) or Test(10)
Test(10)
However if you use them in an if
statement the if
will also implicitly call bool
on the result. So these finer points may not be relevant for you.
How do you get the logical xor of two variables in Python?
Question by Zach Hirsch
How do you get the logical xor of two variables in Python?
For example, I have two variables that I expect to be strings. I want to test that only one of them contains a True value (is not None or the empty string):
str1 = raw_input("Enter string one:")
str2 = raw_input("Enter string two:")
if logical_xor(str1, str2):
print "ok"
else:
print "bad"
The ^
operator seems to be bitwise, and not defined on all objects:
>>> 1 ^ 1
0
>>> 2 ^ 1
3
>>> "abc" ^ ""
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for ^: "str" and "str"
Answer #1:
If you"re already normalizing the inputs to booleans, then != is xor.
bool(a) != bool(b)
Answer #2:
You can always use the definition of xor to compute it from other logical operations:
(a and not b) or (not a and b)
But this is a little too verbose for me, and isn"t particularly clear at first glance. Another way to do it is:
bool(a) ^ bool(b)
The xor operator on two booleans is logical xor (unlike on ints, where it"s bitwise). Which makes sense, since bool
is just a subclass of int
, but is implemented to only have the values 0
and 1
. And logical xor is equivalent to bitwise xor when the domain is restricted to 0
and 1
.
So the logical_xor
function would be implemented like:
def logical_xor(str1, str2):
return bool(str1) ^ bool(str2)
Credit to Nick Coghlan on the Python-3000 mailing list.
Uppercase logical and lowercase letters in PHP: StackOverflow Questions
Meaning of @classmethod and @staticmethod for beginner?
Question by user1632861
Could someone explain to me the meaning of @classmethod
and @staticmethod
in python? I need to know the difference and the meaning.
As far as I understand, @classmethod
tells a class that it"s a method which should be inherited into subclasses, or... something. However, what"s the point of that? Why not just define the class method without adding @classmethod
or @staticmethod
or any @
definitions?
tl;dr: when should I use them, why should I use them, and how should I use them?
Answer #1:
Though classmethod
and staticmethod
are quite similar, there"s a slight difference in usage for both entities: classmethod
must have a reference to a class object as the first parameter, whereas staticmethod
can have no parameters at all.
Example
class Date(object):
def __init__(self, day=0, month=0, year=0):
self.day = day
self.month = month
self.year = year
@classmethod
def from_string(cls, date_as_string):
day, month, year = map(int, date_as_string.split("-"))
date1 = cls(day, month, year)
return date1
@staticmethod
def is_date_valid(date_as_string):
day, month, year = map(int, date_as_string.split("-"))
return day <= 31 and month <= 12 and year <= 3999
date2 = Date.from_string("11-09-2012")
is_date = Date.is_date_valid("11-09-2012")
Explanation
Let"s assume an example of a class, dealing with date information (this will be our boilerplate):
class Date(object):
def __init__(self, day=0, month=0, year=0):
self.day = day
self.month = month
self.year = year
This class obviously could be used to store information about certain dates (without timezone information; let"s assume all dates are presented in UTC).
Here we have __init__
, a typical initializer of Python class instances, which receives arguments as a typical instancemethod
, having the first non-optional argument (self
) that holds a reference to a newly created instance.
Class Method
We have some tasks that can be nicely done using classmethod
s.
Let"s assume that we want to create a lot of Date
class instances having date information coming from an outer source encoded as a string with format "dd-mm-yyyy". Suppose we have to do this in different places in the source code of our project.
So what we must do here is:
- Parse a string to receive day, month and year as three integer variables or a 3-item tuple consisting of that variable.
- Instantiate
Date
by passing those values to the initialization call.
This will look like:
day, month, year = map(int, string_date.split("-"))
date1 = Date(day, month, year)
For this purpose, C++ can implement such a feature with overloading, but Python lacks this overloading. Instead, we can use classmethod
. Let"s create another "constructor".
@classmethod
def from_string(cls, date_as_string):
day, month, year = map(int, date_as_string.split("-"))
date1 = cls(day, month, year)
return date1
date2 = Date.from_string("11-09-2012")
Let"s look more carefully at the above implementation, and review what advantages we have here:
- We"ve implemented date string parsing in one place and it"s reusable now.
- Encapsulation works fine here (if you think that you could implement string parsing as a single function elsewhere, this solution fits the OOP paradigm far better).
cls
is an object that holds the class itself, not an instance of the class. It"s pretty cool because if we inherit our Date
class, all children will have from_string
defined also.
Static method
What about staticmethod
? It"s pretty similar to classmethod
but doesn"t take any obligatory parameters (like a class method or instance method does).
Let"s look at the next use case.
We have a date string that we want to validate somehow. This task is also logically bound to the Date
class we"ve used so far, but doesn"t require instantiation of it.
Here is where staticmethod
can be useful. Let"s look at the next piece of code:
@staticmethod
def is_date_valid(date_as_string):
day, month, year = map(int, date_as_string.split("-"))
return day <= 31 and month <= 12 and year <= 3999
# usage:
is_date = Date.is_date_valid("11-09-2012")
So, as we can see from usage of staticmethod
, we don"t have any access to what the class is---it"s basically just a function, called syntactically like a method, but without access to the object and its internals (fields and another methods), while classmethod does.
Answer #2:
Rostyslav Dzinko"s answer is very appropriate. I thought I could highlight one other reason you should choose @classmethod
over @staticmethod
when you are creating an additional constructor.
In the example above, Rostyslav used the @classmethod
from_string
as a Factory to create Date
objects from otherwise unacceptable parameters. The same can be done with @staticmethod
as is shown in the code below:
class Date:
def __init__(self, month, day, year):
self.month = month
self.day = day
self.year = year
def display(self):
return "{0}-{1}-{2}".format(self.month, self.day, self.year)
@staticmethod
def millenium(month, day):
return Date(month, day, 2000)
new_year = Date(1, 1, 2013) # Creates a new Date object
millenium_new_year = Date.millenium(1, 1) # also creates a Date object.
# Proof:
new_year.display() # "1-1-2013"
millenium_new_year.display() # "1-1-2000"
isinstance(new_year, Date) # True
isinstance(millenium_new_year, Date) # True
Thus both new_year
and millenium_new_year
are instances of the Date
class.
But, if you observe closely, the Factory process is hard-coded to create Date
objects no matter what. What this means is that even if the Date
class is subclassed, the subclasses will still create plain Date
objects (without any properties of the subclass). See that in the example below:
class DateTime(Date):
def display(self):
return "{0}-{1}-{2} - 00:00:00PM".format(self.month, self.day, self.year)
datetime1 = DateTime(10, 10, 1990)
datetime2 = DateTime.millenium(10, 10)
isinstance(datetime1, DateTime) # True
isinstance(datetime2, DateTime) # False
datetime1.display() # returns "10-10-1990 - 00:00:00PM"
datetime2.display() # returns "10-10-2000" because it"s not a DateTime object but a Date object. Check the implementation of the millenium method on the Date class for more details.
datetime2
is not an instance of DateTime
? WTF? Well, that"s because of the @staticmethod
decorator used.
In most cases, this is undesired. If what you want is a Factory method that is aware of the class that called it, then @classmethod
is what you need.
Rewriting Date.millenium
as (that"s the only part of the above code that changes):
@classmethod
def millenium(cls, month, day):
return cls(month, day, 2000)
ensures that the class
is not hard-coded but rather learnt. cls
can be any subclass. The resulting object
will rightly be an instance of cls
.
Let"s test that out:
datetime1 = DateTime(10, 10, 1990)
datetime2 = DateTime.millenium(10, 10)
isinstance(datetime1, DateTime) # True
isinstance(datetime2, DateTime) # True
datetime1.display() # "10-10-1990 - 00:00:00PM"
datetime2.display() # "10-10-2000 - 00:00:00PM"
The reason is, as you know by now, that @classmethod
was used instead of @staticmethod
Answer #3:
@classmethod
means: when this method is called, we pass the class as the first argument instead of the instance of that class (as we normally do with methods). This means you can use the class and its properties inside that method rather than a particular instance.
@staticmethod
means: when this method is called, we don"t pass an instance of the class to it (as we normally do with methods). This means you can put a function inside a class but you can"t access the instance of that class (this is useful when your method does not use the instance).
What is the meaning of single and double underscore before an object name?
Can someone please explain the exact meaning of having single and double leading underscores before an object"s name in Python, and the difference between both?
Also, does that meaning stay the same regardless of whether the object in question is a variable, a function, a method, etc.?
Answer #1:
Single Underscore
Names, in a class, with a leading underscore are simply to indicate to other programmers that the attribute or method is intended to be private. However, nothing special is done with the name itself.
To quote PEP-8:
_single_leading_underscore: weak "internal use" indicator. E.g. from M import *
does not import objects whose name starts with an underscore.
Double Underscore (Name Mangling)
From the Python docs:
Any identifier of the form __spam
(at least two leading underscores, at most one trailing underscore) is textually replaced with _classname__spam
, where classname
is the current class name with leading underscore(s) stripped. This mangling is done without regard to the syntactic position of the identifier, so it can be used to define class-private instance and class variables, methods, variables stored in globals, and even variables stored in instances. private to this class on instances of other classes.
And a warning from the same page:
Name mangling is intended to give classes an easy way to define “private” instance variables and methods, without having to worry about instance variables defined by derived classes, or mucking with instance variables by code outside the class. Note that the mangling rules are designed mostly to avoid accidents; it still is possible for a determined soul to access or modify a variable that is considered private.
Example
>>> class MyClass():
... def __init__(self):
... self.__superprivate = "Hello"
... self._semiprivate = ", world!"
...
>>> mc = MyClass()
>>> print mc.__superprivate
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: myClass instance has no attribute "__superprivate"
>>> print mc._semiprivate
, world!
>>> print mc.__dict__
{"_MyClass__superprivate": "Hello", "_semiprivate": ", world!"}
Answer #2:
__foo__
: this is just a convention, a way for the Python system to use names that won"t conflict with user names.
_foo
: this is just a convention, a way for the programmer to indicate that the variable is private (whatever that means in Python).
__foo
: this has real meaning: the interpreter replaces this name with _classname__foo
as a way to ensure that the name will not overlap with a similar name in another class.
No other form of underscores have meaning in the Python world.
There"s no difference between class, variable, global, etc in these conventions.