[Tutor] using If statement with chaining of conditional operators
Manprit Singh
manpritsinghece at gmail.com
Wed Sep 9 02:55:16 EDT 2020
Dear Sir ,
Consider a problem of finding the greatest of 3 numbers , that are assigned
to three variables . The simple solution is to write :
>>> a = 3
>>> b = 7
>>> c = 4
>>> max(a, b, c)
7
Which is the right answer.
now if i have to solve this using if statement , I would prefer to write
this solution as given below :
a = 4
b = 2
c = 9
if b < a > c:
print(a)
elif b > c:
print(b)
else:
print(c)
In the if part, you can see i have written if b < a > c: , this is chaining
of comparison operators which says b is smaller than a and a is greater
than c.
If this condition is true then print a . I have seen this if clause is
written in
several places as given below :
if (a > b) and (a > c):
print(a)
Need your suggestions, what to prefer in this particular case.
Second point where i need your suggestions , about the codes written below:
The problem is there are 2 variables a and b , each variable is assigned a
number by the user. Now if the number assigned to both variables is 3 then
i have to increase the value of both variables by 2 and do nothing if the
number assigned to both variables is not 3 , and at last print the value of
both variables
The code is written below :
a = int(input("input 1st number"))
b = int(input("Input 2nd number"))
if a == 3 == b:
a, b = a +2, b + 2
print(a, b)
In an another similar case ,as the case just given above, the difference
now is,
if the values assigned to both variables a and b is None, then assign 0 to
both variables else do nothing , and at last print the values of both
variables.I would prefer to write the if statement for this problem as
follows :
if a is None is b:
a, b = 0, 0
Need your suggestions and comments
Third case where i need your guidance is, if i have 4 variables a, b, c, d
and each variable is assigned a value , now if the number assigned to all
these variable is 3 then i have to increase the value of all these values
by 2, else do nothing. And at last print values of all these values.
Now in that case, i am not convinced by the code written by myself, which
is written below :
a = int(input("input 1st number"))
b = int(input("Input 2nd number"))
c = int(input("Input 3rd number"))
d = int(input("Input 4th number"))
if a == b == c == d == 3:
a, b, c, d = a + 2, b + 2, c + 2, d + 2
print(a, b, c, d)
See, the point which is giving problem to me is, in the if block of the
code just written above , first checks that all variables are equal and
then at last it is checking that all variables are equal to 3 , that logic
seems little odd to me. kindly correct if my views are wrong.
Thanks & regards
Manprit Singh
print(a, b)
More information about the Tutor
mailing list