DEV Community

dongdiri
dongdiri

Posted on

DAY 9: Python Day 12

Namespace and scope

  • function has local scope
  • blocks like for, while, if do not
  • can tap into global variable with global keyword within a function (avoid modifying global scope; prone to bugs) -alternatively, use return -CONSTANTS are usually given global scope and are capitalized by convention.

End of the Lesson Project: number guessing game

#Number Guessing Game Objectives:

# 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
run_project = True 

while run_project:
  number = random.randrange(1, 101)
  print("Welcome to the Number Guessing Game!")
  print("I'm thinking of a number between 1 and 100.")
  difficulty = input("Choose a difficulty. Type 'easy' or 'hard':" )
  def game(attempts): 
    for i in range(1, attempts + 1):
      print(f"You have {attempts+1-i} attempts remaining to guess the number.")
      guess = int(input("Make a guess:" ))
      if guess > number:
        print("Too high.")
      elif guess < number: 
        print("Too low.")
      else: 
        print(f"You got it! The answer was {number}.")
        return 
  if difficulty == "easy": 
    game (10)
  elif difficulty == "hard":
    game (5)

  if input("Restart game? 'yes' or 'no'") == "yes":
    run_project = True
  else: 
    run_project = False
Enter fullscreen mode Exit fullscreen mode

As this project was made some scratch, some improvements can be made:

  • store number of turns as a global variable, which was the whole point of today's lesson
  • create another function to set the difficulty
  • do not forget that return exits the function!

Top comments (0)