Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.5k 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 Reply

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...