简单的条件运算符python

时间:2019-03-01 11:42:29

标签: python

我是编程的新手。有什么方法可以简化条件运算符

a = 50; b = 70; c = 60; 

# Classification 

if (a == b and b == c and c ==a):
   print('Equilateral triangle')

elif (a == b or b == c or c == a):
   print('Isosceles triangle')

elif (a!=b and b!=c and c!=a):
   print('Scalene triangle')

2 个答案:

答案 0 :(得分:6)

您可以使用chained comparisons来缩短使用and的比较,并使用else来代替其中一个测试(它们是互斥的):

if a == b == c:
   print('Equilateral triangle')

elif a != b != c != a:
   print('Scalene triangle')

else:
   print('Isosceles triangle')

请注意,Python的if语法在测试表达式周围不需要任何括号。

接下来,您可以将这些值视为集合,并测试集合中有多少个元素:

unique_lengths = len({a, b, c})

if unique_lengths == 1:
   print('Equilateral triangle')

elif unique_lengths == 2:
   print('Isosceles triangle')

else:
   print('Scalene triangle')

然后可以将其转换为列表查找,将123映射到三角形类名称;我将None放到0位置:

classes = [None, 'Equilateral', 'Isosceles', 'Scalene']
print(classes[len({a, b, c})], 'triangle')

答案 1 :(得分:0)

使用列表:

lis = [a,b,c]
lis.sort()
if lis[0] == lis[-1]:
    print("Equilateral triangle")
elif lis[0] == lis[1] or lis[-1] == lis[1]:
    print("Isosceles triangle")
else:
    print("Scalene triangle")