This question already has answers here:
Python ? (conditional/ternary) operator for assignments [duplicate]
(2 answers)
Closed 7 years ago.
I Java it's possible to represent IF-THEN statement in the following form:
a = (x==10) ? true : false;
that is equivalent to
if (x==10)
a=true;
else
a=false;
Is it possible to do the same thing in Python?
a = True if x == 10 else False
or simply
a = x == 10
Related
This question already has answers here:
The tilde operator in Python
(9 answers)
Closed 1 year ago.
pd_selftest = pd_selftest[pd_selftest['SICCD'] != 0]
pd_selftest = pd_selftest[~pd_selftest['SICCD'].isnull()]
I'd like to know what the function of the ~ is in the above code.
That's the bit-wise invert or not operator. So, it returns only those lines where the SICCID column is not null. I would probably use the word not in this case.
This question already has answers here:
Is False == 0 and True == 1 an implementation detail or is it guaranteed by the language?
(3 answers)
Closed 2 years ago.
Why "~False" is -1 in Python?
I was using a boolean variable in Python. When I try to do not of that, it returns -1. I want to understand why so? why a variable a changing its data-type duo to this operation.
Trying to add more details
b0 = False
print(type(b0))
b0 = ~b0
print(type(b0))
>>bool
>>int
The tilde ~ is the bitwise 'not' operator, not the boolean 'not' operator. To do a not you probably want 'not False'.
The reason for it changing its data type is that it treats False as binary 0 and then flips it to -1.
This question already has answers here:
Negation in Python
(4 answers)
Closed 2 years ago.
I have a function which returns true/false. Now I tried to use in a condicional, like this:
isOdd = lambda n: True if n%2 != 0 else False
if !isOdd(2):
print('Yey')
but I got SyntaxError: invalid syntax
how could I use ! in a function like this? it looks like this only works if:
if isOdd(2) == False:
print('Yey')
I don't believe Python uses ! for negation like C does. Try
if not isOdd(2):
This question already has answers here:
Does Python evaluate if's conditions lazily? [duplicate]
(7 answers)
Closed 4 years ago.
print(True or 5 / 0 > 3)
This is my code but it returns True
Is there a reason why it doesn't return a Zero Division Error?
Its because True is always true. The Python interpreter does not evaluate the right side of the or operator in this case, because the outcome of an or expression is always true if one of its operands is true. If you enter5 / 0 > 3 or True than you get your devision by zero error
This question already has answers here:
Math operations from string [duplicate]
(8 answers)
Closed 6 years ago.
I have a string with a formula 5 - 3, and I need to get the result in integer. How could I do that?
use eval function:
eval("5 - 3") # 2
test = "5-3"
print(eval(test))
Gives 2