Selection · 选择(分支)
Programs make choices
- Selection means the program picks what to do based on a condition.
- A condition is a question that is
TrueorFalse. - This is a key idea in AP CSP: code that decides.
程序会做选择
- 选择(selection)是指程序根据一个条件来决定做什么。
- 条件是一个结果为
True或False的问题。 - 这是 AP CSP 的核心思想:会做判断的代码。
if / elif / else
ifruns its block only when the condition isTrue.elif("else if") checks another condition if the ones above wereFalse.elseruns when none of the conditions wereTrue.
if / elif / else
if只有当条件为True时才运行它的代码块。elif(“否则如果”)在上面的条件都为False时再检查另一个条件。else在所有条件都不为True时运行。
hour = 14
if hour < 12:
print("Morning")
elif hour < 18:
print("Afternoon")
else:
print("Evening")
Comparisons make conditions
==equal,!=not equal,<><=>=.==tests if two values are equal; a single=stores a value.- The result of a comparison is
TrueorFalse.
比较运算产生条件
==等于,!=不等于,<><=>=。==检测两个值是否相等;单个=是存储一个值。- 比较运算的结果是
True或False。
score = 72
print(score >= 50)
print(score == 100)
Boolean logic: and / or / not
andisTrueonly when both sides areTrue.orisTruewhen at least one side isTrue.notflips it:not TrueisFalse.
布尔逻辑:and / or / not
- 只有两边都为
True时,and才为True。 - 只要至少有一边为
True,or就为True。 not会取反:not True是False。
age = 16
if age >= 13 and age <= 19:
print("Teenager")
else:
print("Not a teenager")
In AP CSP pseudocode
- Python
if/elsematches CB'sIF(condition){ } ELSE { }. - CB uses words for logic:
AND,OR,NOT. DISPLAY= print,←==.
用 AP CSP 伪代码表示
- Python 的
if/else对应 CB 的IF(condition){ } ELSE { }。 - CB 用单词来表示逻辑:
AND、OR、NOT。 DISPLAY= print,←==。
IF (score >= 50)
{
DISPLAY "Pass"
}
ELSE
{
DISPLAY "Fail"
}
IF ((age >= 13) AND (age <= 19))
{
DISPLAY "Teenager"
}
Common mistakes
- Compare with
==, not=. - Indent the block that runs when the condition is true.
常见错误
- 比较用
==,不是=。 - 缩进条件为真时运行的语句块。
Now you try
- Read each task to see what to print or check.
- Match the output text exactly.
现在轮到你
- 阅读每个任务,看清要打印或检查什么。
- 输出文字要完全一致。
Selection picks a branch · 选择结构挑一个分支
Conditions are tested in order; the first true one runs. · 条件按顺序检查;第一个为真的运行。
Read a score with int(input()). Print A if it is 80 or more, B if it is 60 or more, otherwise C. Use if / elif / else. For input 75, print B. · 用 int(input()) 读取一个分数。如果是 80 及以上打印 A,60 及以上打印 B,否则打印 C。使用 if / elif / else。当输入为 75 时,打印 B。
Click Run to see the output here. · 点击“运行”查看此处输出。
temp is 22. Set comfortable to · 到 True when temp is from 18 to · 到 25 (inclusive), else False. Use one comparison with and. · temp 是 22。当 temp 在 18 到 25 之间(含两端)时,把 comfortable 设为 True,否则为 False。用一个带 and 的比较。
Click Run to see the output here. · 点击“运行”查看此处输出。
day is "Sun" and is_holiday is False. Print Day off if it is a weekend ("Sat" or · 或 "Sun") or · 或 a holiday; otherwise print Work day. Use or. · day 是 "Sun",is_holiday 是 False。如果是周末("Sat" 或 "Sun")或节假日,就打印 Day off,否则打印 Work day。用 or。
Click Run to see the output here. · 点击“运行”查看此处输出。