Selection
This page needs a recent browser (with SharedArrayBuffer support). Please update Chrome, Edge, Firefox or Safari to the latest version. · 이 페이지는 최신 브라우저(SharedArrayBuffer 지원)가 필요합니다. Chrome, Edge, Firefox 또는 Safari를 최신 버전으로 업데이트해 주세요.
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.
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.
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.
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.
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,←==.
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.
Explore · 탐색하기
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.
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.
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.
Click Run to see the output here. · 출력을 보려면 '실행'을 클릭하세요.