Jos
Jos

Reputation: 137

using 'or' in python always evaluate to true and it can clash with other conditions

I am writing a simple Boolean expression in Python that should follow this set of rules:

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

Answers (5)

Aga Qul
Aga Qul

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

sahasrara62
sahasrara62

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)

  1. yes reservation when either you or date is >=8 (have 1 more condition, none of them should be <=2).

  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

Kien Nguyen
Kien Nguyen

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

Jakub Szlaur
Jakub Szlaur

Reputation: 2132

  1. The code gives you the result 2 because the condition you>=8 or date>=8 has priority over the others.
  2. The code goes through one condition at a time. And executes the code of the first condition that returns Truthy value.

Check out this article about Truthy and Falsy values.

Upvotes: 6

lllrnr101
lllrnr101

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

Related Questions