Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

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:

  • The parameter "you" is the stylishness of your clothes, in the range 0..10, and "date" is the stylishness of your date's clothes in the same range.
  • The result getting the table is encoded as an int value with 0=no, 1=maybe, 2=yes.
  • 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). 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.

question from:https://stackoverflow.com/questions/65918953/using-or-in-python-always-evaluate-to-true-and-it-can-clash-with-other-conditi

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
  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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...