코딩을 배우는 것은 단순히 튜토리얼을 읽는 것이 아닙니다. 직접 팔을 걷어붙이고 연습하는 것입니다. 이 포스트에서는 초보자에게 완벽한 20가지 간단한 연습문제를 살펴보겠습니다. 각 연습문제에는 예제와 Python 솔루션이 포함되어 있어 즉시 시도해 볼 수 있습니다.
1. "Hello, World!" 출력하기
연습문제가 원하는 것: 화면에 메시지를 출력하는 가장 간단한 프로그램을 작성하세요. 이는 코드를 실행하고 가시적인 결과를 얻는 방법을 보여줍니다.
사용할 것: print() 함수 — 입력 없이 출력만 합니다.
샘플 출력
Hello, World!
Python 솔루션
print("Hello, World!")
2. 간단한 계산기
연습문제가 원하는 것: 사용자로부터 두 숫자를 입력받아 합, 차, 곱, 몫을 계산하세요. 이는 입력 처리와 기본 산술을 배우는 데 도움이 됩니다.
사용할 것: input()으로 숫자를 받고, float()으로 변환하며, 산술 연산자 (+ - * /)와 print()로 결과를 출력합니다.
샘플 입력
8
2
샘플 출력
Addition: 10.0
Subtraction: 6.0
Multiplication: 16.0
Division: 4.0
Python 솔루션
a = float(input("Enter first number: ").strip())
b = float(input("Enter second number: ").strip())
print("Addition:", a + b)
print("Subtraction:", a - b)
print("Multiplication:", a * b)
print("Division:", a / b if b != 0 else "Infinity")
3. 홀수 또는 짝수 확인기
연습문제가 원하는 것: 정수가 홀수인지 짝수인지 결정하세요.
사용할 것: 나머지 %, 조건부 표현식
샘플 입력
7 is odd
샘플 출력
7 is odd
Python
n = int(input().strip())
print(f"{n} is {'even' if n % 2 == 0 else 'odd'}")
4. 숫자 맞추기 게임
연습문제가 원하는 것: 컴퓨터가 랜덤 숫자를 선택하고, 사용자가 맞출 때까지 계속 추측하며 높거나 낮다는 힌트를 제공합니다.
사용할 것: random.randint(), while 루프, if/elif/else.
샘플 실행
Guess (1-10): 5
Too low
Guess (1-10): 8
Correct!
Python 솔루션
import random
secret = random.randint(1, 10)
while True:
g = int(input("Guess (1-10): ") or 0)
if g < secret:
print("Too low")
elif g > secret:
print("Too high")
else:
print("Correct!")
break
5. 구구단
연습문제가 원하는 것: 주어진 숫자에 대해 1–10 구구단을 출력하세요.
사용할 것: for 루프, f-strings.
샘플 입력
3
샘플 출력
3 x 1 = 3
...
3 x 10 = 30
Python 솔루션
n = int(input().strip())
for i in range(1, 11):
print(f"{n} x {i} = {n*i}")
6. 팰린드롬 확인기
연습문제가 원하는 것: 텍스트가 앞뒤로 읽었을 때 같은지 확인하세요 (대소문자 및 공백/구두점 무시).
사용할 것: 문자열 정리, .lower(), 슬라이싱 [::-1].
샘플 입력
RaceCar
샘플 출력
RaceCar is a palindrome
Python 솔루션
s = input().strip()
clean = ''.join(ch.lower() for ch in s if ch.isalnum())
print(f"{s} is {'a palindrome' if clean == clean[::-1] else 'not a palindrome'}")
7. 피보나치 수열
연습문제가 원하는 것: 처음 n개의 피보나치 수를 출력하세요.
사용할 것: 마지막 두 값을 추적하는 변수, for 루프, 리스트 조인.
샘플 입력
6
샘플 출력
0 1 1 2 3 5
Python 솔루션
n = int(input().strip())
a, b = 0, 1
seq = []
for _ in range(n):
seq.append(str(a))
a, b = b, a + b
print(' '.join(seq))
8. 팩토리얼 계산기
연습문제가 원하는 것: n! (1부터 n까지의 곱)을 계산하세요.
사용할 것: for 루프 곱셈 (또는 재귀).
샘플 입력
5
샘플 출력
120
Python 솔루션
n = int(input().strip())
f = 1
for i in range(2, n+1):
f *= i
print(f)
9. 단어 수 세기
연습문제가 원하는 것: 문장에 몇 개의 단어가 있는지 세세요.
사용할 것: str.split(), len().
샘플 입력
I love programming
샘플 출력
3
Python 솔루션
s = input().strip()
print(len(s.split()))
10. 할 일 목록 (미니 CLI)
연습문제가 원하는 것: 간단한 반복 메뉴에서 작업을 추가하고, 보기 및 제거하세요.
사용할 것: 리스트, while 루프, if/elif/else.
샘플 실행
1
Finish homework
2
1 Finish homework
Python 솔루션
tasks = []
while True:
print("1) Add 2) View 3) Remove 4) Exit")
c = input("> ").strip()
if c == "1":
tasks.append(input("Task: ").strip()); print("Added.")
elif c == "2":
if tasks:
for i, t in enumerate(tasks, 1):
print(i, t)
else:
print("No tasks.")
elif c == "3":
i = int(input("Index: ") or 0)
if 1 <= i <= len(tasks):
tasks.pop(i-1); print("Removed.")
else:
print("Invalid index.")
elif c == "4":
break
else:
print("Try 1-4.")
11. 문자열 뒤집기
연습문제가 원하는 것: 입력 텍스트의 뒤집힌 버전을 출력하세요.
사용할 것: 슬라이싱 [::-1].
샘플 입력
hello
샘플 출력
olleh
Python 솔루션
print(input().strip()[::-1])
12. 세 숫자 중 가장 큰 수
연습문제가 원하는 것: 세 숫자를 읽고 가장 큰 수를 출력하세요.
사용할 것: input().split(), map(), max().
샘플 입력
4 9 2
샘플 출력
9
Python 솔루션
a, b, c = map(float, input().split())
print(max(a, b, c))
13. 온도 변환기 (C ↔ F)
연습문제가 원하는 것: 섭씨를 화씨로 또는 그 반대로 변환하세요.
사용할 것: 조건문, 산술.
샘플 입력
C 25
샘플 출력
77.0
Python 솔루션
scale, val = input().split()
x = float(val)
print(x * 9/5 + 32 if scale.upper() == 'C' else (x - 32) * 5/9)
14. 단순 이자 계산기
연습문제가 원하는 것: P, R, T를 사용하여 단순 이자를 계산하세요.
사용할 것: map(float, ...), 산술 공식 P*R*T/100.
샘플 입력
1000 5 2
샘플 출력
100.0
Python 솔루션
P, R, T = map(float, input().split())
print(P * R * T / 100)
15. 소수 확인기
연습문제가 원하는 것: n이 소수인지 알려주세요.
사용할 것: √n까지 반복, 약수에서 조기 종료.
샘플 입력
13
샘플 출력
prime
Python 솔루션
n = int(input().strip())
if n < 2:
print("not prime")
else:
i, ok = 2, True
while i*i <= n:
if n % i == 0:
ok = False; break
i += 1
print("prime" if ok else "not prime")
16. 숫자 합
연습문제가 원하는 것: 입력된 모든 숫자 문자를 더하세요.
사용할 것: 문자열에 대한 생성기 표현식, sum().
샘플 입력
1234
샘플 출력
10
Python 솔루션
s = input().strip()
print(sum(int(ch) for ch in s if ch.isdigit()))
17. 모음 세기
연습문제가 원하는 것: 입력 텍스트에 모음이 몇 개 있는지 세세요.
사용할 것: .lower(), 집합을 사용한 포함 여부 확인.
샘플 입력
programming
샘플 출력
3
Python 솔루션
s = input().lower()
vowels = set('aeiou')
print(sum(ch in vowels for ch in s))
18. 가위 바위 보
연습문제가 원하는 것: 컴퓨터와 한 판 대결을 하고 승/패/무를 보고하세요.
사용할 것: random.choice(), 튜플 기반 승리 규칙, if/elif.
샘플 실행
rock
Computer chose: scissors
You win!
Python 솔루션
import random
user = input("rock/paper/scissors: ").strip().lower()
cpu = random.choice(["rock", "paper", "scissors"])
print("Computer chose:", cpu)
if user == cpu:
print("Tie!")
elif (user, cpu) in {("rock","scissors"), ("paper","rock"), ("scissors","paper")}:
print("You win!")
else:
print("You lose!")
19. 리스트에서 최소값 & 최대값
연습문제가 원하는 것: 한 줄에 숫자를 읽고 최소값과 최대값을 출력하세요.
사용할 것: split(), map(float), min(), max().
샘플 입력
5 9 1 7 3
샘플 출력
1 9
Python 솔루션
nums = list(map(float, input().split()))
print(min(nums), max(nums))
20. 기본 비밀번호 검증기
연습문제가 원하는 것: 비밀번호를 검증하세요: 길이 ≥ 8, 문자와 숫자가 각각 하나 이상 포함되어야 합니다.
사용할 것: len(), any(), .isalpha(), .isdigit(), 불리언 논리.
샘플 입력
Hello123
샘플 출력
valid
Python 솔루션
pw = input().strip()
ok = (len(pw) >= 8 and any(ch.isalpha() for ch in pw) and any(ch.isdigit() for ch in pw))
print("valid" if ok else "invalid")