在 Python 中,if、elif(“else and if”的缩合)和 else 语句用来控制执行流程,并在程序中做出判断。
与许多其他编程语言不同,Python 3.9 及更早的版本没有提供正式的 case-switch 语句,而是用多个elif语句来实现类似的目的。
Python 3.10 引入了一种变体的 case-switch 语句,叫做structural pattern matching,它会在另一个概念中单独讲解。
分支语句使用的表达式必须求值为True或False,既可以直接返回bool类型,也可以按照“truthy”或“falsy”来求值。
x = 10
y = 5
# The comparison '>' returns the bool 'True',
# so the statement is printed.
if x > y:
print("x is greater than y")
...
>>> x is greater than y
当和if搭配使用时,如果原本的if条件的求值结果为False,那么可选的else代码块就会执行:
x = 5
y = 10
# The comparison '>' here returns the bool 'False',
# so the 'else' block is executed instead of the 'if' block.
if x > y:
print("x is greater than y")
else:
print("y is greater than x")
...
>>> y is greater than x
elif允许进行多次求值和分支。
x = 5
y = 10
z = 20
# The 'elif' statement allows for the checking of more conditions.
if x > y:
print("x is greater than y and z")
elif y > z:
print("y is greater than x and z")
else:
print("z is greater than x and y")
...
>>> z is greater than x and y
>>> def classic_fizzbuzz(number):
if number % 3 == 0 and number % 5 == 0:
say = 'FizzBuzz!'
elif number % 5 == 0:
say = 'Buzz!'
elif number % 3 == 0:
say = 'Fizz!'
else:
say = str(number)
return say
>>> classic_fizzbuzz(15)
'FizzBuzz!'
>>> classic_fizzbuzz(13)
'13'
在本练习中,我们将为一个核反应堆开发一套简单的控制系统。
反应堆要产生功率,就必须处于_临界_状态。 如果反应堆的状态低于临界,就可能受损。 如果反应堆的状态超过临界,就会过载并导致熔毁。 我们希望能降低熔毁的风险,并正确地管理反应堆的状态。
以下三个任务都与编写代码来维持理想反应堆状态有关。
控制系统要做的第一件事,就是检查反应堆是否处于_临界平衡_状态。 满足以下条件时,就称反应堆处于临界平衡:
实现函数 is_criticality_balanced(),它接受以开尔文为单位的 temperature 和 neutrons_emitted 作为形参,如果满足临界条件就返回 True,否则返回 False。
>>> is_criticality_balanced(750, 600)
True
一旦反应堆开始产生功率,就需要确定它的效率。 效率可以分为 4 个区间:
green -> 效率在 80% 或以上,orange -> 效率低于 80%,但不低于 60%,red -> 效率低于 60%,但仍然不低于 30%,black -> 效率低于 30%。百分比数值可以用 (generated_power/theoretical_max_power)*100 计算,其中 generated_power = voltage * current。
注意,百分比数值通常不是整数,所以要确保正确使用 < 和 <= 这两种比较。
实现函数 reactor_efficiency(<voltage>, <current>, <theoretical_max_power>),它有三个形参:voltage、current 和 theoretical_max_power。
这个函数应返回反应堆的效率区间:'green'、'orange'、'red' 或 'black'。
>>> reactor_efficiency(200,50,15000)
'orange'
你的最后一个任务是创建一个故障安全机制,以避免过载和熔毁。 这个机制将判断反应堆是低于、正好处于还是高于理想的临界阈值。 之后,就可以通过向反应堆中插入(或拔出)控制棒来提高、降低或停止临界状态。
实现函数 fail_safe(),它接受 3 个形参:以开尔文为单位的 temperature、neutrons_produced_per_second 和 threshold,并输出反应堆的状态代码。
如果 temperature * neutrons_produced_per_second < threshold 的 90%,则输出状态代码 'LOW',表示必须拔出控制棒才能产生功率。
如果 temperature * neutrons_produced_per_second 的值在 threshold 的 10% 范围内(也就是比阈值低 0-10%、正好等于阈值,或比阈值高 0-10%),反应堆就处于_临界_状态,此时应输出状态代码 'NORMAL',表示反应堆处于最佳状态,控制棒也处于理想位置。
如果 temperature * neutrons_produced_per_second 不在上述范围内,反应堆就即将熔毁,必须传出状态代码 'DANGER',立即关闭反应堆。
>>> fail_safe(temperature=1000, neutrons_produced_per_second=30, threshold=5000)
'DANGER'