Python中的三目运算符

语法格式

Python语言不像Java、JavaScript等这些语言有类似:

 判段的条件?条件为真时的结果:条件为假时的结果

这样的三目运算,但是Python也有自己的三目运算符:   

 条件为真时的结果 if 判段的条件 else 条件为假时的结果

举例

例一:编写一个Python程序,输入两个数,比较它们的大小并输出其中较大者。

x = int(input("please enter first integer:"))
y = int(input("please enter second integer:"))

#一般的写法
 if (x == y):
     print("两数相同!")
 elif(x > y):
     print("较大的数为:",x)
 else:
     print("较大的数为:",y)

# 三目运算符写法
print(x if(x>y) else y)
Last modification:January 13th, 2021 at 08:57 pm
如果觉得我的文章对你有用,请随意赞赏