[udemy ] python 부트캠프 _ section 12_유효 범위와 숫자 맞추기 게임

Dreamer ·2022년 8월 21일
0
post-thumbnail

01. 네임스페이스 : 전역 vs 지역범위

  • Scope(유효범위) : 전역범위, 지역범위의 차이는 변수를 지정한 범위의 차이임. 전역 변수는 함수 안에서 사용 가능함. 함수 외부에서도 사용가능함.
  • Namespace : 모든 대상에는 이름공간이 있음.
enemies = 1

def increase_enemies():
  enemies = 2
  print(f"enemies inside function: {enemies}")

increase_enemies()
print(f"enemies outside function: {enemies}")

02. 전역변수를 수정하는 방법

  • 전역변수를 절대로 지역범위 변수를 가진 함수 내에서는 수정하지 말 것!
enemies = 1

def increase_enemies():
  global enemies
  enemies += 1
  print(f"enemies inside function: {enemies}")

increase_enemies()
print(f"enemies outside function: {enemies}")
nemies = 1

def increase_enemies():
  print(f"enemies inside function: {enemies}")
  return enemies + 1
  
enemies = increase_enemies()
print(f"enemies outside function: {enemies}")

03. 파이썬 상수와 전역적 유효 범위 파이썬 상수와 전역적 유효 범위

  • 전역범위를 가진 변수를 사용할 때는 조심해야 함! 굉장히 유용하므로 정수를 정의할 때 강력히 편함. pi와 같은 값임. 한 번 찾아서 코드에 입력 한 후 다시 수정하지 않으므로!
  • 상수는 변경하지 않으므로, 변수명을 모두 대문자로 사용함! 변수와 다름
PI = 3.14159
URL : "https://www.google.com" 
TWITTER_HANDLE = "@yu_angela"

04. quiz

#Number Guessing Game Objectives:
# Include an ASCII art logo.
# Allow the player to submit a guess for a number between 1 and 100.
# Check user's guess against actual answer. Print "Too high." or "Too low." depending on the user's answer. 
# If they got the answer correct, show the actual answer to the player.
# Track the number of turns remaining.
# If they run out of turns, provide feedback to the player. 
# Include two different difficulty levels (e.g., 10 guesses in easy mode, only 5 guesses in hard mode).

import random
from art import logo 
from replit import clear

print(logo)

def guessing():
  level = input("Welcom to the Number Guessing Game! \n I'm thinking of a number between 1 and 100. Choose a difficulty. Type 'easy' or 'hard':  ")
  
  answer = random.choice(range(100))

  if level == "easy":
    remain_game = 10
    print(f"You have {remain_game} attempts remaining to guess the number.")
  elif level == "hard":
    remain_game = 5
    print(f"You have {remain_game} attempts remaining to guess the number.")
  else:
    "You choose wrong answer!"
      
  while remain_game != 0:
    guess = int(input("Make a guess: "))   
    if guess < answer:
      remain_game -=1
      print(f"Too low! \n Guess again. \n You have {remain_game} attempts remaining to guess the number.")
      
    elif guess > answer:
      remain_game -= 1
      print(f"Too high! \n Guess again. \n You have {remain_game} attempts remaining to guess the number.")
    
    elif guess == answer:
      print(f"You got it! The answer was {answer}")
      remain_game = 0
  
guessing()

while input("Do you want to play a game again? Type 'y' or 'n': ") == "y":
  clear()
  guessing()
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()
  • 위의 내 함수와 아래의 선생님의 함수의 경우 RAM 차이가 극명히 차이가 난다. 나의 경우 하나의 함수에 모든 걸 다 넣었기에 계속해서 함수가 불러져 오기에 메모리를 많이 차지한다. 코드의 수정이 필요하다.
profile
To be a changer who can overturn world

0개의 댓글