흐름 제어 · 08
참·거짓 값과 삼항 연산자
참·거짓을 변수에 담아 두기, 두 값 중 하나 고르기, "이 중 하나인가" 묻기.
조건문 단원에서는 비교를 if 안에서 바로 썼어요.
이번에는 그 결과를 값으로 다뤄요.
아래 예제는 요일과 손님들의 나이를 읽어서, 주말인지와 어린이가 있는지를 변수에 담아 두고, 주말이면 12, 평일이면 8인 입장료의 합을 찍어요.
day = input().strip()ages = list(map(int, input().split())) weekend = day in ("sat", "sun") # 포함 검사의 결과(참·거짓)를 변수에 담아요child = False # 깃발: 아직 어린이를 못 봤어요for age in ages: if age < 13: child = True price = 12 if weekend else 8 # 두 값 중 하나를 골라요print("weekend" if weekend else "weekday")print(price * len(ages))print("child" if child else "adults")const lines = require("fs").readFileSync(0, "utf8").split("\n");const day = lines[0].trim();const ages = lines[1].trim().split(/\s+/).map(Number); const weekend = ["sat", "sun"].includes(day); // 포함 검사의 결과(참·거짓)를 변수에 담아요let child = false; // 깃발: 아직 어린이를 못 봤어요for (const age of ages) { if (age < 13) child = true;} const price = weekend ? 12 : 8; // 두 값 중 하나를 골라요console.log(weekend ? "weekend" : "weekday");console.log(price * ages.length);console.log(child ? "child" : "adults");import { readFileSync } from "node:fs";const lines: string[] = readFileSync(0, "utf8").split("\n");const day: string = lines[0].trim();const ages: number[] = lines[1].trim().split(/\s+/).map(Number); const weekend: boolean = ["sat", "sun"].includes(day); // 포함 검사의 결과(참·거짓)를 변수에 담아요let child: boolean = false; // 깃발: 아직 어린이를 못 봤어요for (const age of ages) { if (age < 13) child = true;} const price: number = weekend ? 12 : 8; // 두 값 중 하나를 골라요console.log(weekend ? "weekend" : "weekday");console.log(price * ages.length);console.log(child ? "child" : "adults");import java.util.List;import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); String day = sc.nextLine().strip(); String[] ages = sc.nextLine().strip().split(" +"); boolean weekend = List.of("sat", "sun").contains(day); // 포함 검사의 결과(참·거짓)를 변수에 담아요 boolean child = false; // 깃발: 아직 어린이를 못 봤어요 for (String age : ages) { if (Integer.parseInt(age) < 13) child = true; } int price = weekend ? 12 : 8; // 두 값 중 하나를 골라요 System.out.println(weekend ? "weekend" : "weekday"); System.out.println(price * ages.length); System.out.println(child ? "child" : "adults"); }}using System;using System.Linq; class Program{ static void Main() { string day = Console.ReadLine().Trim(); string[] ages = Console.ReadLine().Split(' ', StringSplitOptions.RemoveEmptyEntries); string[] rest = { "sat", "sun" }; bool weekend = rest.Contains(day); // 포함 검사의 결과(참·거짓)를 변수에 담아요 bool child = false; // 깃발: 아직 어린이를 못 봤어요 foreach (string age in ages) { if (int.Parse(age) < 13) child = true; } int price = weekend ? 12 : 8; // 두 값 중 하나를 골라요 Console.WriteLine(weekend ? "weekend" : "weekday"); Console.WriteLine(price * ages.Length); Console.WriteLine(child ? "child" : "adults"); }}#include <algorithm>#include <iostream>#include <string>#include <vector> int main() { std::string day; std::cin >> day; std::vector<int> ages; int age; while (std::cin >> age) ages.push_back(age); std::vector<std::string> rest = {"sat", "sun"}; bool weekend = std::find(rest.begin(), rest.end(), day) != rest.end(); // 포함 검사의 결과(참·거짓)를 변수에 담아요 bool child = false; // 깃발: 아직 어린이를 못 봤어요 for (int a : ages) { if (a < 13) child = true; } int price = weekend ? 12 : 8; // 두 값 중 하나를 골라요 std::cout << (weekend ? "weekend" : "weekday") << '\n'; std::cout << price * ages.size() << '\n'; std::cout << (child ? "child" : "adults") << '\n';}#include <stdbool.h>#include <stdio.h>#include <string.h> int main(void) { char day[16]; int ages[100], n = 0; scanf("%15s", day); while (scanf("%d", &ages[n]) == 1) n++; const char *rest[] = {"sat", "sun"}; bool weekend = false; // 포함 검사 도구가 없어서 하나씩 견줘요 for (int i = 0; i < 2; i++) { if (strcmp(day, rest[i]) == 0) weekend = true; } bool child = false; // 깃발: 아직 어린이를 못 봤어요 for (int i = 0; i < n; i++) { if (ages[i] < 13) child = true; } int price = weekend ? 12 : 8; // 두 값 중 하나를 골라요 printf("%s\n", weekend ? "weekend" : "weekday"); printf("%d\n", price * n); printf("%s\n", child ? "child" : "adults"); return 0;}day = 콘솔.줄읽기().공백제거();ages = 콘솔.수들읽기(); // 포함 검사의 결과(참·거짓)를 변수에 담아요weekend = ["sat", "sun"].있나(day);// 깃발: 아직 어린이를 못 봤어요child = 거짓;각각 (age 에서 ages){ 만약 (age < 13) { child = 참; }} // 두 값 중 하나를 골라요price = weekend ? 12 : 8;콘솔.쓰기(weekend ? "weekend" : "weekday");콘솔.쓰기(price * ages.개수);콘솔.쓰기(child ? "child" : "adults");sat 35 41 9
weekend 36 child
핵심
- 비교의 결과(
age < 13)는 참·거짓 값이에요.
수나 문자열처럼 변수에 담아 두고 여러 번 쓸 수 있어요.
담아 둔 값은 조건 자리에 그대로 써요.if (weekend)면 되고== true는 붙이지 않아요. - 깃발은 참·거짓 변수를 반복과 함께 쓰는 꼴이에요.
반복 앞에서 거짓으로 두고, 찾던 것을 만나면 참으로 바꿔요.
반복이 끝나면 "하나라도 있었나"가 남아요. - 삼항 연산자는 조건에 따라 두 값 중 하나를 골라요.
if는 할 일을 고르고, 삼항은 값을 골라요.
그래서 대입의 오른쪽이나 출력 안에 바로 넣을 수 있어요. - 삼항은 짧을 때만 써요.
삼항 안에 또 삼항을 넣게 되면if와else로 풀어 쓰는 쪽이 읽기 쉬워요. - 포함 검사는 "이 값이 이것들 중 하나인가"를 물어요.
==를||로 길게 잇는 대신, 값들을 목록에 담고 "들어 있나"를 한 번만 물어요.
답은 참·거짓이에요. - 참·거짓을 그대로 출력하면 언어마다 달라요.
Python과 C#은True, JavaScript·Java·크레이콘은true, C와 C++는1이에요.
그래서 예제는 삼항으로 문자열을 골라서 찍어요.
언어별로 쓰는 법
| Python | weekend = day in ("sat", "sun"), 깃발은 child = False에서 True로.삼항은 12 if weekend else 8 — 참일 때의 값이 맨 앞에 와요.아니다는 not weekend |
|---|---|
| JavaScript | const weekend = ["sat", "sun"].includes(day);, 삼항은 weekend ? 12 : 8.in은 포함 검사가 아니에요."sat" in ["sat", "sun"]은 false예요(값이 아니라 번호가 있는지 물어요) |
| TypeScript | JavaScript와 같아요. 타입 이름은 boolean이에요 |
| Java | boolean weekend = List.of("sat", "sun").contains(day);, 삼항은 weekend ? 12 : 8.문자열 하나와 견줄 때는 day.equals("sat") |
| C# | bool weekend = rest.Contains(day); — 배열에 쓰려면 using System.Linq;가 있어야 해요.삼항은 weekend ? 12 : 8 |
| C++ | bool weekend = std::find(rest.begin(), rest.end(), day) != rest.end();(<algorithm>), 삼항은 weekend ? 12 : 8.bool을 그대로 찍으면 1이고, std::boolalpha를 먼저 보내면 true |
| C | #include <stdbool.h>를 넣어야 bool, true, false를 쓸 수 있어요.포함 검사 도구가 없어서 반복으로 하나씩 strcmp(day, rest[i]) == 0인지 봐요.글자 하나는 strchr("aeiou", c) != NULL.삼항은 weekend ? 12 : 8 |
| Craykon | weekend = ["sat", "sun"].있나(day);, 깃발은 child = 거짓;에서 참으로.삼항은 weekend ? 12 : 8.문자열에도 "aeiou".있나("e")처럼 물을 수 있어요 |
자주 하는 실수
깃발을 else에서 다시 거짓으로 돌렸어요
int[] ages = {9, 35, 41};
boolean child = false;
for (int age : ages) {
if (age < 13) child = true;
else child = false;
}
System.out.println(child ? "child" : "adults");→ adults — 9살이 있는데 어린이가 없대요. 9에서 참이 됐다가 35와 41에서 다시 거짓으로 덮였어요. 이렇게 쓰면 깃발에는 "마지막 손님이 어린이인가"만 남아요. 어느 언어로 써도 똑같아요
else를 지워요.
깃발은 반복 앞에서 한 번만 거짓으로 두고, 반복 안에서는 참으로 바꾸기만 해요.
반복 안에서 child = age < 13;처럼 매번 새로 담아도 같은 실수예요.
== "sat" or "sun"으로 둘 중 하나인지 물었어요Python · JavaScript · TypeScript · C · C++ · Craykon
day = "mon"
if day == "sat" or "sun":
print("weekend")
else:
print("weekday")→ weekend — 월요일인데 주말이래요. (day == "sat") or "sun"으로 읽혀서, 앞이 거짓이면 "sun"이 조건이 되는데 빈 문자열이 아니라서 참이에요
양쪽을 모두 비교로 써요(day == "sat" or day == "sun").
포함 검사로 쓰면 더 짧아요(day in ("sat", "sun")).
Java와 C#은 이 코드를 컴파일 오류로 막아 줘요.
삼항을 괄호 없이 + 뒤에 붙였어요JavaScript · TypeScript · Python · C++ · Craykon
const ok = false;
console.log("Result: " + ok ? "yes" : "no");→ yes — +가 먼저 계산돼요. "Result: false"라는 문자열이 조건이 되고, 빈 문자열이 아니라서 늘 참이에요. 크레이콘도 yes를 찍어요. Python의 "Result: " + "yes" if ok else "no"는 no만 찍고, C++의 std::cout << ok ? "yes" : "no";는 0을 찍어요
삼항 전체를 괄호로 감싸요: "Result: " + (ok ? "yes" : "no").
Java와 C#은 괄호가 없으면 컴파일 오류로 알려 줘요.
조건 자리에 참·거짓이 아닌 값을 넣었을 때 언어가 둘로 갈려요.
Java와 C#은 컴파일 오류로 막아요.
C·C++·Python·JavaScript·TypeScript·크레이콘은
"sun" 같은 값도 참으로 보고 지나가요.무엇을 거짓으로 보는지도 언어마다 달라요.
빈 목록은 Python에서는 거짓이지만 JavaScript와 크레이콘에서는 참이에요.
첫 번째와 세 번째 실수가 조용히 틀린 답을 내는 까닭이에요.
조건에는 비교나 참·거짓 변수만 넣는 버릇을 들이면 안전해요.