Day 012

AWESOMee·2022년 2월 2일
0

Udemy Python Bootcamp

목록 보기
12/64
post-thumbnail

Udemy Python Bootcamp Day 012

Scope

Local scope
Local scope exists within funcions.
when we create a new variable or indeed a new funcion inside another function, it's only accessible. we can only use it when we're inside that function because it has local scope.

Global scope
It's available anywhere within output file because it was defined at the top of the file.

The only difference global scope and local scope is where we define or where we create variables or functions.
This concept of global and local scope doesn't just apply to variables. It also applies to functions and basically anything else we name.

#ex.
player_health = 10 # global scope

def game():
  def drink_potion():
    potion_strength = 2 # local scope
    pront(player_health)
  
  drink_potion

print(player_health)

There is no Block Scope

game_level = 3
def create_enemy():
  enemies = ["Skeleton", "Zombie", "Alien"]
  if game_level < 5:
    new_enemy = enemies[0]

  print(new_enemy)

Modifying Global Scope

enemies = "Skeleton"

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

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

#output
enemies inside function: Zombie
enemies outside function: Skeleton

Global

global which is called 'enemies' that's defined somewhere outside of this funtion.

enemies = 1

def increase_enemies():
  global enemies
  enemies += 1
  #that is the enemies that we want to use inside this function.
  print(f"enemies inside function: {enemies}")

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

What if instead of modifying the 'enemies', we actually just simply returned it as the output.

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

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

Global Constants
GLobal constants are variables which we define and we're never planning on changing it ever again.

PI = 3.141592
URL = "http://velog.io/@awesomee"
TWITTER_HANDLE = "@jjolev_escape"

Guess the Number Game

TODO

  • Choosing a random number between 1 and 100.
  • Make function to set difficulty.
  • Let the user guess a number,
  • Function to check user's guess against actual answer.
  • Track the number of turns and reduce by 1 if they get it wrong.
  • Repeat the guessing functionality if they get it wrong.
#What i wrote

import random
from art import logo
print(logo)

print("Welcome to the Number Guessing Game!")
print("I'm thinking of a number between 1 and 100.")
answer = random.randint(1, 100)
print(f"Pssst, the correct answer is {answer}")
difficulty = input("Choose a difficulty. Type 'easy' or 'hard': ").lower()

if difficulty == "easy":
  attempt = 10
else:
  attempt = 5


def user_guess():
  global answer, guessed
  if guessed == answer:
    print(f"You got it! The answer was {answer}.")
  elif guessed < answer:
    print("Too low.\nGuess again.")
  else:
    print("Too high.\nGuess again.")

while attempt > 0 or guessed == answer:
  print(f"You have {attempt} attempts remaining to guess the number.")
  guessed = int(input("Make a guess: "))
  user_guess()
  attempt -= 1

여기까지 했는데,,
guessed == answer일때 문구 출력하고 끝내는게 안됨..
while구문에 넣어놨으니까 멈춰야 하는거 아니냐고,,
왜 자꾸 You have {attempt} attempts remaining to guess the number. 가 출력되는데 ㅠㅠ

guessed = 0
while guessed != answer:

while loop 이렇게 바꾸니까 정답 입력하면 멈추긴 하는데
문제는 attempt = 0 일 때 안끝난다는 거임...
애초부터 내 함수가 문제였나..

#Solution
from random import randint
from art import logo

EASY_LEVEL_TURNS = 10 #Global scope
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()

답이 하나는 아니겠지만..
이렇게 풀이하는 방식이 꽤나 다를때마다 좀 현타옴 ㅎ;

profile
개발을 배우는 듯 하면서도

0개의 댓글