Reputation: 137
I am writing a simple Boolean expression in Python that should follow this set of rules:
int
value with
0=no
, 1=maybe
, 2=yes
.2 (yes)
. With the exception that if either of you has style of 2
or
less, then the result is 0 (no)
. Otherwise the result is 1 (maybe)
.My code works fine except for a certain condition. What if you have a styling of 8 and your date has a styling or 2 or less? Which result should run and why? Here is my code
def date_fashion(you, date):
if you>=8 or date>=8:
return 2
elif you<=2 or date<=2:
return 0
else:
return 1
if I run date_fashion(10, 2) it should give 0, but it also could give 2.
Which one is the right answer? here both conditions clash at the same time which one is correct? Result 0 or result 2 and why? My code gives 2 but it could also give 0.
Upvotes: 1
Views: 410
Reputation: 19
def date_fashion(you, date):
condition1=(you>2 and date>2) and (you>=8 or date>=8)
condition2=(you<=2 or date<=2)
if condition1:
return 2
elif condition2:
return 0
else:
return 1
Upvotes: 0
Reputation: 11228
try to make priority in defining conditions, from certain to less certain conditions.
eg.
1.no reservation when either you or date is <=2 (definitive)
yes reservation when either you or date is >=8 (have 1 more condition, none of them should be <=2).
maybe reservation in other case
so by defining the less dependent first and than move on to next lvl (here point 2, where it only cancel when point 1 is true) so on and then a last making a general solution here maybe
, then you can solve.
def date_fashion(you, date):
if you<=2 or date<=2:
return 0
elif you>=8 or date>=8:
return 2
return 1
Upvotes: 1
Reputation: 2691
If you run date_fashion(10, 2)
it will always return 2
and never 0
. Because you=10
satisfies condition you>=8
, then the function executes the return 0
statement and immediately stops. In that case the next statements will not be run.
Upvotes: 1
Reputation: 2132
2
because the condition you>=8 or date>=8
has priority over the others.condition
that returns Truthy
value.Check out this article about
Truthy and Falsy
values.
Upvotes: 6
Reputation: 2343
For your condition: If either of you is very stylish, 8 or more, then the result is 2 (yes). With the exception that if either of you has style of 2 or less, then the result is 0 (no), you should put the exception before the normal condition. So then when you see a <2 you return 0.
def date_fashion(you, date):
if you<=2 or date<=2:
return 0
elif you>=8 or date>=8:
return 2
else:
return 1
Upvotes: 2