gpt4 book ai didi

python - 区分条件语句的各种编写风格

转载 作者:行者123 更新时间:2023-12-01 01:17:35 25 4
gpt4 key购买 nike

我不明白为什么Python中的一些代码是没有缩进的。

两个函数都做同样的事情,但是为什么第一个函数 is_leap1 的编写风格只有 return 而没有 if 语句?第一个函数如何在不使用 if 和 else 的情况下返回 True 和 False:?

def is_leap1(year):
return year % 4==0and(year %100 !=0 or year %400==0)

print(is_leap1(2014))

def is_leap2(year):
if (( year%400 == 0)or (( year%4 == 0 ) and ( year%100 != 0))):
return True
else:
return False

print(is_leap2(2014))

输出

False
False

最佳答案

比较运算符,例如 == , != , < , >= , and , or等等,自然都会返回 bool 值。因此,您不需要使用 if返回语句TrueFalse使用这些运算符时。您可以自己简单地测试一下:

print(5 > 3)                     # True
print(True if 5 > 3 else False) # True

official documentation明确这一点:

Comparisons yield boolean values: True or False.

关于python - 区分条件语句的各种编写风格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54173535/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com