업무에 파이썬 활용할 줄 알기
Day12 | 초급 | 유효 범위와 숫자 맞추기 게임 복습 본문
Day12 | 초급 | 유효 범위와 숫자 맞추기 게임 복습
SEO 데이터분석가 2023. 12. 20. 17:13네임스페이스: 지역 vs. 전역 범위 (Namespaces: Local vs. Global Scope)
def안에서 만들어지는 이름들(변수,...?)은 def 바깥에서 사용할 수 없다
파이썬도 블록 유효 범위가 있나요? (Does Python have Block Scope?)
if, for, while과 같은 함수에서 indented가 되어 작성되는 변수들은 범위를 가지지 않는다.
def()안에서 if, for, while이 작성되는게 아닌 이상
전역 변수를 수정하는 방법 (How to Modify Variables with Global Scope)
def문 안에서 global 변수를 선언하지 않고는 global 변수를 def문안에서 수정할 수 없다
그러나 이런 방식으로 전역변수를 수정하는건 최대한 피하는게 좋다
수정한다면 return을 활용
파이썬 상수와 전역적 유효 범위 (Python Constants & Global Scope)
절대 수정하지 않을 상수에 대해서
대문자 변수로 나타내면 수정될 일 없는 전역 변수라는 것을 알 수 있다
실행화면 나눠보기
flowchart를 잘 만들어 주는게 어렵다..
My solution
print("Welcome to the Number Guessing Game!")
print("I'm thinking of a number between 1 and 100.")
#정답 세팅하기
import random
answer = random.randint(1,100)
easy_or_hard = input("Choose a difficulty. Type 'easy' or 'hard': ")
#게임횟수설정
if easy_or_hard == 'easy':
num_of_game = 10
elif easy_or_hard == 'hard':
num_of_game = 5
is_game_over = False
while not is_game_over:
print(f"You have {num_of_game} attempts remaining to guess the number.")
guess = int(input("Make a guess: "))
num_of_game -= 1
if guess == answer:
print(f"You got it! The answer was {answer}.")
is_game_over = True
else:
if num_of_game > 0:
if guess > answer:
print("Too high.")
print("Guess again.")
elif guess < answer:
print("Too low.")
print("Guess again.")
else:
print("You've run out of guesses, you lose.")
is_game_over = True
※ randint(a,b): a,b를 모두 포함한다
시행착오 과정
모범답안처럼 def문을 잘 활용하지는 못했지만 정상적으로 작동은 된다.
다만 하나 잘못한게 마지막 게임에서 틀렸을 때 Too high, Too low를 반환하도록 설계하지 않은 점이다
<플로우차트 잘못된 점>
<플로우차트 수정 후>
모범답안
from random import randint
from art import logo
EASY_LEVEL_TURNS = 10
HARD_LEVEL_TURNS = 5
#Function to check user's guess against actual answer.
def check_answer(guess, answer, turns):
"""checks answer against guess. Returns the number of turns remaining."""
if guess > answer:
print("Too high.")
return turns - 1
elif guess < answer:
print("Too low.")
return turns - 1
else:
print(f"You got it! The answer was {answer}.")
#Make function to set difficulty.
def set_difficulty():
level = input("Choose a difficulty. Type 'easy' or 'hard': ")
if level == "easy":
return EASY_LEVEL_TURNS
else:
return HARD_LEVEL_TURNS
def game():
print(logo)
#Choosing a random number between 1 and 100.
print("Welcome to the Number Guessing Game!")
print("I'm thinking of a number between 1 and 100.")
answer = randint(1, 100)
print(f"Pssst, the correct answer is {answer}")
turns = set_difficulty()
#Repeat the guessing functionality if they get it wrong.
guess = 0
while guess != answer:
print(f"You have {turns} attempts remaining to guess the number.")
#Let the user guess a number.
guess = int(input("Make a guess: "))
#Track the number of turns and reduce by 1 if they get it wrong.
turns = check_answer(guess, answer, turns)
if turns == 0:
print("You've run out of guesses, you lose.")
return
elif guess != answer:
print("Guess again.")
game()
모범답안 반영된 flowchart
전역변수를 수정하지 않는 다른 방법
1번의 방법으로도 전역변수 turns를 수정하는게 가능하기는 하나
전역벽수를 local scope내에서 수정하는 것은 지양하는게 좋음
따라서, 전역변수를 수정하지 않고 2번과 같이
turns 숫자를 가져와서 return을 해준다
게임끝 빠져나오는 방법
게임이 끝났는데도 계속 while반복문이 실행될 때, return을 써서 빠져나올 수 있다
배운 점
def문을 짜서 활용하는게 여전히 어렵다
혼자서는 생각하지 못할 법한 코드들이 다수 적용되었는데, 다음과 같다.
- def check_answer(guess, answer, turns)와 파라메터를 3개나 넣고 함수를 만들어 준 것
- turns = check_answer(guss, answer, turns)로 turns변수에 지정해준 것 (turns는 마지막에 실행후 디버깅하면서 추가)
- guess를 0으로 전역변수로 먼저 지정하고 while문을 작성한 것
- easy or hard 선택 조차도 def set_difficulty()로 함수를 생성해주고 횟수를 전역상수를 활용하여, print가 아니라 return을 시켜준 것
11일차 강의와 다르게 이번에는 flowchart로 먼저 정교하게 구조를 갖춘게 아니라
심플하게 구조를 쪼갠 다음 만들면서 코드를 수정해나가더라. 이런 방법도 괜찮다는 것!
'Python > [Udemy] 100개의 프로젝트로 Python 개발 완전 정복' 카테고리의 다른 글
Day 18 | 중급 | 터틀 & 그래픽 사용자 인터페이스 (GUI) (2) | 2024.01.02 |
---|---|
Day17 | 중급 | 퀴즈 프로젝트와 OOP의 장점 (0) | 2023.12.28 |
Day16 | 중급 | 객체 지향 프로그래밍(OOP) (0) | 2023.12.27 |
Day15 | 중급 | 커피 머신 프로젝트 (0) | 2023.12.26 |
Day11 | 초급 | 블랙잭 게임 프로젝트 (0) | 2023.12.18 |