0
点赞
收藏
分享

微信扫一扫

Kaggle翻译,第三天:Python 3/7

穆熙沐 2022-03-21 阅读 70

布尔值和条件——Python3/7

布尔值

Python有一种变量类型叫bool。他有两个可能的值:TrueFalse

x = True
print(x)
print(type(x))
True
<class 'bool'>
  • 除了在我们的代码中直接使用TrueFalse,我们通常从布尔运算符获取布尔值。这些运算符回答是/否的问题。我们会在下面学习这些运算符。

比较运算符

运算符描述运算符描述
a == ba等于ba != ba不等于b
a < ba小于ba > ba大于b
a <= ba小于等于ba >= ba大于等于b
def can_run_for_president(age):
    """Can someone of the given age run for president in the US?"""
    # The US Constitution says you must be at least 35 years old
    return age >= 35

print("Can a 19-year-old run for president?", can_run_for_president(19))
print("Can a 45-year-old run for president?", can_run_for_president(45))
Can a 19-year-old run for president? False
Can a 45-year-old run for president? True
  • 比较运算结果通常和我们的期望值一样。
3.0 == 3
True
  • 但有的时候会很棘手。
'3' == 3
False
  • 比较运算符可与我们学过的算术运算符组合表达一个几乎无限的数学测试的范围。例如,我们可以检查一个数模2是否返回1判断一个数是否为奇数:
def is_odd(n):
    return (n % 2) == 1

print("Is 100 odd?", is_odd(100))
print("Is -1 odd?", is_odd(-1))
Is 100 odd? False
Is -1 odd? True
  • 当进行比较时,记得使用==而不是=。如果你写了n==2你是问关于n的值。当你写n=2时,你正在改变n的值。

组合布尔值

  • 您可以将布尔值使用标准的概念"and","or"和"not"进行组合。事实上,要做到这一点的词是:andornot
  • 这样我们可以使can_run_for_president函数更加准确:
def can_run_for_president(age, is_natural_born_citizen):
    """Can someone of the given age and citizenship status run for president in the US?"""
    # The US Constitution says you must be a natural born citizen *and* at least 35 years old
    return is_natural_born_citizen and (age >= 35)

print(can_run_for_president(19, True))
print(can_run_for_president(55, False))
print(can_run_for_president(55, True))
False
False
True
  • 快,看看你能不能猜出这个表达式的值
True or True and False
True
  • 要回答这个问题,你需要弄清比较运算的顺序。
  • 例如,andor 之前运算。这就是为什么上面的结果是True。如果我们从左向右计算,我们就会先算True or True(得到True),然后算与False的结果,最后得到False
  • 你可以尝试记忆运算顺序,但安全是使用括号。这不仅有助于防止bug,它使你的意图更加明确,方便读取您的代码的任何人。
  • 例如考虑下面的表达式:
prepared_for_weather = have_umbrella or rain_level < 5 and have_hood or not rain_level > 0 and is_workday
  • 我想说今天的天气不会影响到我……
    • 如果我带了雨伞
    • 或者雨不太大而且我戴了顶帽子
    • 除非今天下雨而且是工作日。
  • 但不仅是我的Python代码难以阅读,它还有一个bug。我们可以解决这两个问题增加了一些括号:
prepared_for_weather = have_umbrella or (rain_level < 5 and have_hood) or not (rain_level > 0 and is_workday)
  • 你还可以添加更多括号方便阅读。
prepared_for_weather = have_umbrella or ((rain_level < 5) and have_hood) or (not (rain_level > 0 and is_workday))
  • 你还可以分多行来强调三段不同的描述:
prepared_for_weather = (
    have_umbrella 
    or ((rain_level < 5) and have_hood) 
    or (not (rain_level > 0 and is_workday))
)

条件

  • 布尔值有时结合条件语句是最有用的,使用关键字,if elif,以及else
  • 条件语句,通常称为if-then语句,让您控制哪些代码片段是基于一些布尔条件的值。下面是一个示例:
def inspect(x):
    if x == 0:
        print(x, "is zero")
    elif x > 0:
        print(x, "is positive")
    elif x < 0:
        print(x, "is negative")
    else:
        print(x, "is unlike anything I've ever seen...")

inspect(0)
inspect(-15)
0 is zero
-15 is negative
  • ifelse关键字通常用于其他语言;它更独特的关键字是elif,收缩"else if"。在这些条件状语从句,elifelse块是可选的;另外,你可以包含任意多个elif语句。
  • 尤其要注意使用冒号(:)和空白指单独的代码块。这类似于当我们定义了一个函数的函数头:和下面的行缩进4个空格。所有后续行缩进属于函数体,直到我们遇到一个未缩进的行,结束函数定义。
def f(x):
    if x > 0:
        print("Only printed when x is positive; x =", x)
        print("Also only printed when x is positive; x =", x)
    print("Always printed, regardless of x's value; x =", x)

f(1)
f(0)
Only printed when x is positive; x = 1
Also only printed when x is positive; x = 1
Always printed, regardless of x's value; x = 1
Always printed, regardless of x's value; x = 0

布尔转换

  • 我们见过了int(),将值转换成整数型,float()将值转换成浮点型,那么Python中的bool()将值转换成布尔型也就不奇怪了吧。
print(bool(1)) # all numbers are treated as true, except 0
print(bool(0))
print(bool("asf")) # all strings are treated as true, except the empty string ""
print(bool(""))
# Generally empty sequences (strings, lists, and other types we've yet to see like lists and tuples)
# are "falsey" and the rest are "truthy"
True
False
True
False
  • 我们可以使用非布尔对象,如果条件和其他地方期待一个布尔值。Python将隐式地把他们当作其相应的布尔值:
if 0:
    print(0)
elif "spam":
    print("spam")
spam
举报

相关推荐

0 条评论