有没有一种方法可以从两个if条件获得输出?

时间:2019-12-03 20:56:15

标签: python windows

我从Python开始,并且与该语言紧密相连,但是我有一个小问题,当我尝试检查用户是男性还是高个子时,程序运行正常。

但是当我尝试检查用户是否是男性而不是高个子时,程序仅打印第一个。

is_male = True
is_tall = False


if is_male or is_tall:
     print ("You are a male or tall or both")

elif is_male and not (is_tall):
     print ("You are a male but not tall")

else:
     print ("You are not a male or tall!")

我得到的输出是:“您是男性,还是个高个子,或者两者都是”

首先要达到的目标是:“你是男性,但不高”

5 个答案:

答案 0 :(得分:0)

此代码将涵盖您的所有可能性:

if is_male or is_tall:
     print ("You are a male or tall or both")

if is_male and is_tall:
    pass
elif not is_male and is_tall:
    pass
elif is_male and not (is_tall):
     print ("You are a male but not tall")
else:
     print ("You are not a male or tall!")

第一个if仅将is_male or is_tall作为一个单独的语句覆盖。

答案 1 :(得分:0)

您需要重组if条件。问题是,您的方法无法达到秒,因为它的逻辑方程为:

(not (is_male or is_tall)) and (is_male and not is_tall) = (not is_male and is_tall) and is_male and not is_tall) = (is_tall) and (is_male and not is_male) = False 只是一些基于De Morgan's laws的逻辑规则。第一个条件存在是因为您有一个elif,因此第一个if条件必须为False。

或者简单地说:每次有男性时,第一个条件就是“真”。

可能的重组解决方案:

  • 嵌套条件
  • 仅在有条件的情况下使用

嵌套条件

if is_male:
    if is_tall:
        print("male and tall")
    else:
        print("Male but not tall")
else:
    if is_tall:
        print("not male and tall")
    else:
        print("not male and not tall")

仅在语句中

if male and tall:
     print("male and tall")
if male and not tall:
     print("male and not tall")
if not male and tall:
     print("not male and tall")
if not male and not tall:
     print("not male and not tall")

答案 2 :(得分:0)

如果条件(无elif)用于每次打印

is_male = True
is_tall = False


if is_male or is_tall:
     print ("You are a male or tall or both")

if is_male and not is_tall:
     print ("You are a male but not tall")

if not is_male and not is_tall:
     print ("You are not a male or tall!")

答案 3 :(得分:0)

这很简单。只有在前面的“ if”和“ elif”没有执行的情况下,才能执行“ else”或“ elif”。

换句话说,Python像这样查看您的代码:

  • if is_male or is_tall:“好的,is_male是真实的,所以or是真实的,所以if是满意的。”
  • print ("You are a male or tall or both"):“好的,如果满足,那么我应该这样做。现在打印You are a male or tell or both。”
  • elif is_male and not (is_tall):“好吧,这是另外一个,如果以前的条件很满意,那么我就不会看这个。”
  • else:“好吧,这是另外一个,如果以前的条件很满意,那么我就不会看这个。”

如果要同时打印两条消息,则需要将它们分开。

if is_male or is_tall:
    print ("You are a male or tall or both");
if is_male and not (is_tall):
    print ("You are male but not tall");
if not (is_male) and not (is_tall):
    print ("You are not a male or tall");

答案 4 :(得分:-1)

您输入的顺序错误,第一个'if'仅需要(is_male)为真,这就是为什么总是打印“您是男性还是高大或两者兼有”的原因。

尝试:

is_male = True
is_tall = False


if is_male and not (is_tall):
     print ("You are a male but not tall")

elif is_male or is_tall:
     print ("You are a male or tall or both")

else:
     print ("You are not a male or tall!")