3.Booleans and Conditionals

Booleans

Python有bool类型数据,有两种取值:True 和 False.

[1]

x = True
print(x)
print(type(x))
True
<class 'bool'>

我们通常从布尔运算符中获取布尔值,而不是直接在我们的代码中放入True或False。 这些是回答yes或no的运算符。 我们将在下面介绍其中一些运算符。

Comparsion Operations

OperationDescription OperationDescription
a == ba equal to b a != ba not equal to b
a < ba less than b a > ba greater than b
a <= ba less than or equal to b a >= ba greater than or equal to b

[2]

def can_run_for_president(age):
    """Can someone of the given age run for president in the US?"""
    #The US constitution says you must "have attained to the Age of the thirty-five years"
    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_presidnet(45))
    
Can a 19-year-old run for president? False
Can a 45-year-old run for president? True

比较运算有点聪明......

[3]

3.0 == 3
True

但不是很聪明...

[4]

'3' == 3
True

比较运算符可以与我们已经看到的算术运算符组合,以表达无限的数学测试范围。 例如,我们可以通过模2运算来检查数字是否为奇数:

[5]

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的值是否与2相等。 当你写n = 2时,你正在改变n的值。

Combining Boolean Values

Python使用“and”,“or”和“not”的标准概念组合布尔值的运算符。 事实上,相应的Python运算符只使用这些单词:and,or ,not。
有了这些,我们可以使我们的can_run_for_president函数更准确。

[6]

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
    print(can_run_for_president(19, True))
    print(can_run_for_president(55, False))
    print(can_run_for_president(55, True))
    
False
False
True

你能猜出这个表达式的值吗?

[7]

True or True and False
Ture

Python具有优先级规则,用于确定在上述表达式中运算的顺序。 例如,and优先级高于or,这就是上面第一个表达式为True的原因。 如果我们从左到右对它进行运算,我们首先计算True或True(即True),然后计算and False,得到最终值为False。
您可以尝试记住优先顺序,但更安全的选择是使用自由括号。 这不仅有助于防止错误,还可以使您的意图更清晰,任何人都可以阅读您的代码。
例如,请考虑以下表达式:

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))

我们也可以将它拆分成多行来强调上面描述的3部分结构:

prepared_for_weather = (
    have_umbrella 
    or ((rain_level < 5) and have_hood) 
    or (not (rain_level > 0 and is_workday))
)

Conditionals

虽然它们本身就足够有用,但是当与条件语句结合使用时,使用关键字if,elif和else,布尔语句真的开始闪耀。
条件语句(通常称为if-then语句)允许程序员根据某些布尔条件执行某些代码段。 Python条件语句的基本示例是:

[8]

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

Python采用经常用于其它语言的if和else; 它更独特的关键词是elif,是“else if”的缩写。 在这些条件子句中,elif和else块是可选的; 此外,您可以包含任意数量的elif语句。

请特别注意使用冒号(:)和空格来表示单独的代码块。 这与我们定义函数时发生的情况类似 - 函数头以:结尾,后面的行用4个空格缩进。 所有后续的缩进行都属于函数体,直到我们遇到一条未缩进的行,结束函数定义。

[9]

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

Boolean conversion

我们已经看到了int(),它将事物变成了int,而float()将事物变成了浮点数,所以你可能不会惊讶于Python有一个bool()函数可以将事物变成bool。

[10]

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将隐式将它们视为相应的布尔值:

[11]

if 0:
    print(0)
elif "spam":
    print("spam")
spam

Conditional expressions(aka 'ternary')

根据某些条件将变量设置为两个值中的任何一个是一种常见的模式。

[12]

def quiz_message(grade):
    if grade < 50:
        outcome = 'failed'
    else:
        outcome = 'passed'
    print('You', outcome, 'the quiz with a grade of', grade)
    
quiz_message(80)
You passed the quiz with a grade of 80

Python有一个方便的单行“条件表达式”语法来简化这些情况:

[13]

def quiz_message(grade):
    outcome = 'failed' if grade < 50 else 'passed'
    print('You', outcome, 'the quiz with a grade of', grade)
    
quiz_message(45)
You failed the quiz with a grade of 45

您可能会认为这类似于许多其他语言中存在的三元运算符。 例如,在javascript中,我们将上面的赋值写为`var outcome = grade <50? 'failed':'passed'。 (说到可读性,我认为Python在这里是赢家。)

Your turn!

转到练习笔记本,以获得一些boolean和conditionals的实践练习。

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值