Python编程中的决策与条件判断
在计算机编程中,程序具备做出决策的能力是至关重要的。就像火车根据道岔的设置改变轨道一样,程序可以根据输入和其他情况采取不同的行动。下面我们将详细介绍Python中用于实现决策的 if 语句以及相关的关系运算符等内容。
1. if 语句
if 语句用于实现决策。当一个条件满足时,执行一组语句;否则,执行另一组语句。以下是一个使用 if 语句的例子:在许多国家,数字13被认为是不吉利的。为了不冒犯迷信的租户,建筑业主有时会跳过第十三层,第十二层之后紧接着就是第十四层。控制建筑电梯的计算机需要对此进行补偿,并调整所有高于13层的楼层编号。
下面是模拟这个过程的Python代码:
# ch03/elevatorsim.py
##
# This program simulates an elevator panel that skips the 13th floor.
#
# Obtain the floor number from the user as an integer.
floor = int(input("Floor: "))
# Adjust floor if necessary.
if floor > 13 :
actualFloor = floor - 1
else :
actualFloor = floor
# Print the result.
print("The elevator will trave
超级会员免费看
订阅专栏 解锁全文


被折叠的 条评论
为什么被折叠?



