If..else works as OR, does it true? - python

Does if..elif statements works exactly as one OR statement?
For example does below if..elif:
if X == "a":
Y = 1
elif Z == "b" and V = "c":
Y = 1
Works as
if X == "a" or (Z == "b" and V == "c"):
Y = 1

Yes, in your specific case the functionality is the same. You would use an if/elif statement if you were going to do two different things based upon the condition which executes to True. For example,
if a == 'a':
y = 1
elif z == 'b' and v == 'c':
y = 2
However, since in both cases you are doing Y = 1, then
if x == 'a' or (z == 'b' and v == 'c'):
y = 1
works just fine and even is more appropriate.

The effect in your code is the same. But it doesn't work the same way. The or statement looks at the two statements and will return True if at least one of the statements are true. On the other hand, the if...elif statement would just go into one of the conditions. Either only into the if statement, or only into the elif statement.

Related

What are some better alternatives to nesting if statements when comparing 2 values?

Sorry for the wordy title, but I couldn't think of a better way to phrase it. I am comparing 2 values within an if statement. While I would normally do something like this
val = 1
work = input('1 or 2' )
if work == '1':
#must compare value of val
if val == 1:
print('Val is equal to 1')
elif work == '2':
if val == 2:
print('val is equal to 2 ')
#also also compare value of val
All the tutorials say that nesting ifs is a bad practice and will come back to bite you. Is there a better way to do this?
You can put multiple conditions in a single if/elif statement, like so:
if( work == '1') and (val == 1))
#print
elif ( work == '2') and (val == 2))
#print
I believe what you are looking for is the and operator:
val = 1
work = input('1 or 2')
if work == '1' and val == 1:
# do stuff
elif work == '2' and val == 2:
# do stuff

Mistake in function Definition [duplicate]

This question already has answers here:
Why does "a == x or y or z" always evaluate to True? How can I compare "a" to all of those?
(8 answers)
Closed 3 years ago.
I've written a fuction with lots of ELIF and OR statements. Code is working, but result is not what i'm expacting to get - absolutly the same values in DF table i'm cooperating with. What am I doing wrong?
def some_func(x):
if x == "aaaa" or "bbb" or "ccc" or "zzz":
return 1
elif x == "ddd" or "eee" or "fff" or "ggg":
return 2
elif x == "hhh" or "ppp" or "nnn" or "mmm":
return 3
else:
return 0
df.TABLE_name = df.TABLE_name.apply(some_func).astype('int64')
df['TABLE_name'].value_counts()
Out: 1 38133
Although your intuition is correct, the way your code is currently set up, it is not executing how you want.
Writing:
if x == "hello" or "world" does not check to see if x is equal to hello or equal to world. It checks to see if x is equal to hello and automatically returns true, because it essentially is evaluating if("hello"), which would always return true
Your code isn't working properly because your syntax is wrong. Consider making these changes:
def some_func(x):
if x == "aaaa" or x == "bbb" or x == "ccc" or x == "zzz":
return 1
elif x == "ddd" or x == "eee" or x == "fff" or x == "ggg":
return 2
elif x == "hhh" or x == "ppp" or x == "nnn" or x == "mmm":
return 3
else:
return 0
Rather than doing multiple O(n) comparisons in each if/elif statement consider using a set for single O(1) comparison instead:
def some_func(x):
if x in {"aaaa", "bbb", "ccc", "zzz"}:
return 1
elif x in {"ddd", "eee", "fff", "ggg"}:
return 2
elif x in {"hhh", "ppp", "nnn", "mmm"}:
return 3
else:
return 0

function return none instead of return number

I create a function that compare with x and y variable. Inside the function has a lots of nested elif to compare the x and y then return integer. The problem is right now, when it runs at the certain elif statement, it didn't execute the statement although the statement is correct.
def convertTo(self, x, y):
if( x == 0 & y == 0):
return 0
if( x == 0 & y == 1):
return 1
if( x == 0 & y == 2):
return 2
if( x == 0 & y == 3):
return 3
if( x == 1 & y == 0):
return 4 # Didn't return this line even though x = 1 and y = 0
else
return None
def main():
self.convertTo(0,0)
self.convertTo(0,1)
self.convertTo(0,2)
self.convertTo(0,3)
self.convertTo(1,0) # return None? Why?
You're performing a chained equality comparison which is not doing what you think it does. The bitwise & is performed first as it has a higher priority than ==.
Replace:
x == 1 & y == 0
# 1 == 1 & 0 == 0
# 1 == 0 == 0 False!
With:
x == 1 and y == 0
See: Operator precedence
In Python, "&" and "and" do two different things. "and" is what you should be using, "&" is a binary operator.
if
a = 0011 1100
and
b = 0000 1101
then
a&b = 0000 1100
See http://www.tutorialspoint.com/python/python_basic_operators.htm
You should use and instead of &, as & is a bitwise and.
Chaining multiple conditions in Python is generally done with an if-elif-else statement like below:
if a and b:
# a and b both was true
elif a and not b:
# a was true, but b wasn't
else:
# none of the conditions matched
In your code, if it wasn't for the return statement in each if, and the fact that you are checking the same two variables, it would be possible for two if statements to evaluate to true.
if a:
# this will run if a was true
if b:
# regardless of a this will run if b was true
else:
# regardless of a this will only run if b was false
Also, take a look at this: https://docs.python.org/3/tutorial/controlflow.html

Returning using a shortened if else statement in Python

I was going through ways of shortening a normal if else statement.
One of the formats I found was to change this:
if x == 1:
print("Yes")
else:
print("No")
Into this:
print("Yes") if x == 1 else print("No")
Is the code above considered pythonic? Otherwise, what would be a pythonic way of shortening the if else statement?
I also tried using return instead of print. I tried
return total if x == 1 else return half
which resulted in an unreachable statement for the 2nd return. Is there a way of doing it that i'm not able to see?
Finally, I tried to use an else if instead of an else with the code, but that wouldn't work either.
print(total) if x == 1 else print(half) if x == 2
The code above probably looks stupid logic-wise. Am I missing out on the proper format, or is it really not possible to do return and else if with this format?
The form
print("Yes") if x == 1 else print("No")
is not generally considered Pythonic, since ... if ... else ... is an expression and you're throwing away the value that the expression produces (always None). You can use print("Yes" if x == 1 else "No") which is Pythonic since the value of the conditional expression is used as the argument to print.
The form
return total if x == 1 else return half
cannot work since return is a statement and must occur at the beginning of a logical line. Instead, use
return total if x == 1 else half
(which is parsed the same as return (total if x == 1 else half)).
The code
print(total) if x == 1 else print(half) if x == 2
wouldn't work either - the conditional expression is ... if ... else ..., i.e. each if must be paired with an else that follows it; your second if is missing the else clause; you could use
print(total) if x == 1 else print(half) if x == 2 else print('something else')
Again, this wouldn't be considered very pythonic; but you could use
print(total if x == 1 else half if x == 2 else 'something else')
not that it would be much better either.
Finally, if you're participating in a code golf
print("Yes" if x == 1 else "No")
can be shortened to
print(('No', 'Yes')[x == 1])
by using the fact that True == 1 and False == 0 and using these to index a tuple.
Have you tried to use the ternary in the print itself ?
print("Yes" if x == 1 else "No")
A ternary if..else operates on expressions. return is a statement, not an expression. print() is an expression, but note the way you wrote it twice - you're printing regardless; it's just the expression you want to print that may vary.
print("Yes") if x == 1 else print("No")
The above is valid, but you don't need to have two references to the same function:
print("Yes" if x == 1 else "No")
The following is not valid, as you have multiple statements in there:
return total if x == 1 else return half
Again, operate on the expressions you'd like to work with:
return total if x == 1 else half
Now, a ternary is just that - ternary. It should have three parts, not four.
print(total) if x == 1 else print(half) if x == 2
In the above, you have four expressions:
print(total)
x == 1
print(half)
x == 2
That's too many. You can have one of the expressions be, itself, a larger expression, although it does always require an else (to be ternary):
print(total if x == 1 else half if x == 2 else 'Neither 1 nor 2.')
With more parentheses to show grouping:
print(total if x == 1 else (half if x == 2 else 'Neither 1 nor 2.'))
The expression in the inner parentheses above is an expression with a ternary operator itself, as well as an expression in a larger expression with a ternary operator.

Are there sideeffects in python using `if a == b == c: pass;`?

if a == b == c:
# do something
Let's assume a, b, c are string variables. Are there any possible side effects if I use the snippet above to execute # do something if and only if all three strings are equal?
I am asking because I have to check three variables against each other and I get many cases:
if a == b == c:
# do something
elif a == b != c:
# do something
elif a != b == c.
# do something
etc...
Perhaps there is a better way to code this?
There should be no side effects until you use it in a such way.
But take care about things like:
if (a == b) == c:
since it will break chaining and you will be comparing True or False and c value).
From the documentation:
Comparisons can be chained arbitrarily; for example, x < y <= z is equivalent to x < y and y <= z, except that y is evaluated only once (but in both cases z is not evaluated at all when x < y is found to be false).
There should be no side effects.
s = set([a, b, c])
if len(s) == 1:
print 'All equal'
elif len(s) == 3:
print 'All different'
else:
l = list(s)
print '%s and %s are different' % (l[0], l[1])
is there any comment on x!=y!=z ?
i could use the stupid way to get a correct answer.
def aligndigits(list):
return ((x, y , z ) for x in list for y in list for z in list if x != y and y != z and x != z )

Categories

Resources