if-else,在python上使用True和False语句。 skulpt.org

时间:2014-08-14 17:25:46

标签: python if-statement

这是我的代码,我必须创建它才允许

  1. 用户输入三角形的三边长度,如Length1,Length2和Length3
  2. 如果任何双方的长度相同,则程序输出“Isosceles”
  3. 否则程序会输出“Not isosceles”
  4. 然而,输出部分似乎不起作用。 我是这类编码的新手,请帮帮忙?

    Length1 = raw_input()
    Length2 = raw_input()
    Length3 = raw_input()
    
    print Length1
    print Length2
    print Length3
    print Length1 == Length2
    print Length2 == Length3
    print Length1 == Length3
    
    if Length1 == Length2 is True:
        print "Isosceles"
    else: 
        print "Not Isosceles"  
    
    if Length2 == Length3 is True:
        print "Isosceles"
    else:
        print "Not Isosceles"
    
    if Length1 == Length3 is True:
        print "Isosceles"
    else:
        print "Not Isosceles"
    

3 个答案:

答案 0 :(得分:9)

问题在于Python解释

if Length1 == Length2 is True:

if Length1 == Length2 and Length2 is True:

Comparison operators, like <, ==, or is are chained.这对例如非常有用。 a < b < c,但它也可能导致一些意外行为,如您的情况。

将这些支票更改为

if (Length1 == Length2) is True:

或更好,只需使用

if Length1 == Length2:

或者,您可以使用set计算不同方的数量:

distinct_sides = len(set([Length1, Length2, Length3]))
if distinct_sides == 1:
    print "Equilateral"
if distinct_sides == 2:
    print "Isosceles"
if distinct_sides == 3:
    print "Scalene"  

答案 1 :(得分:2)

我只会创建一个函数来检查每一对是否相等

def isosceles(x1, x2, x3):
    return x1 == x2 or x2 == x3 or x1 == x3

# slightly faster version since it returns after the first True
def isosceles(x1, x2, x3):
    return any(x1 == x2, x2 == x3, x1 == x3)

确保您将输入转换为int,这样您就不会比较string

Length1 = int(raw_input())
Length2 = int(raw_input())
Length3 = int(raw_input())

然后调用你的函数

if isosceles(Length1, Length2, Length3):
    print "Isosceles"
else:
    print "Not isosceles"

答案 2 :(得分:1)

if Length1 == Length2: # don't use `if Length1 == Length2 is True:`
    print "Isosceles"

elif Length2 == Length3:
    print "Isosceles"

elif Length1 == Length3:
    print "Isosceles"
else:
    print "Not Isosceles"

您需要使用elifelif's仅在前一个语句为False时进行评估,始终评估if's

if Length1 == Length2 is True:if Length1 == Length2不同:

如果Length1Length2 = True都是{{1}},那么您的陈述只会为真。