Python 숫자 추측 게임
고전적인 초보자용 Python 프로젝트입니다. 무작위 생성, while 루프 및 사용자 입력 유효성 검사를 사용하는 대화형 숫자 추측 게임을 구축하세요.
개요
게임은 프로그래밍 논리와 흐름 제어를 배울 수 있는 환상적인 방법입니다.
이 스크립트는 1에서 100 사이의 난수를 생성한 다음 사용자가 올바른 숫자를 추측할 때까지 "while" 루프에 사용자를 가두어 둡니다.
대상에 대한 추측 상태를 확인하여 힌트(너무 높음, 너무 낮음)를 제공합니다.
코드 및 실행 출력
표준 내장 라이브러리를 활용한 대화형 숫자 추측 루프입니다.
guessing_game.py
에디터에서 사용해 보세요import random
def play_game():
target = random.randint(1, 100)
attempts = 0
print("Welcome to the Number Guessing Game!")
print("I'm thinking of a number between 1 and 100.")
# Simulating a session (since input() blocks in standard runs, we mock it for the demo)
mock_guesses = [50, 75, 60, 65, target]
for guess in mock_guesses:
attempts += 1
print(f"\nYour guess: {guess}")
if guess < target:
print("Too low!")
elif guess > target:
print("Too high!")
else:
print(f"Congratulations! You guessed it in {attempts} attempts!")
break
play_game()터미널 출력
Welcome to the Number Guessing Game!
I'm thinking of a number between 1 and 100.
Your guess: 50
Too low!
Your guess: 75
Too high!
Your guess: 60
Too low!
Your guess: ... (game continues)단계별 구현
- while 루프 전반에 걸친 상태 추적 이해
- 대화형 I/O 스트림을 안전하게 처리
- 논리 게이트 구현
자주 묻는 질문
실제 사용자 입력을 어떻게 사용합니까?
모의 배열 루프를 `while True:` 루프 내에서 `guess = int(input("Enter your 추측: "))`으로 바꾸세요.