Day 12-Scope & Number Guessing Game


Posted by pei_______ on 2022-04-22

learning from 100 Days of Code: The Complete Python Pro Bootcamp for 2022


## local scope & global scope

enemies = 1
## Use global to fix the bug
def increase_enemies():
  global enemies
  enemies = 2
  print(f"enemies inside function: {enemies}")
  """使用時機:用於不想變動的資料
     如:固定變數、網址、聯絡資訊""" 

## Use retrun to fix the bug
def increase_enemies2():
  print(f"enemies inside function: {enemies}")
  return enemies + 1

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

# Number Guessing Game

from random import randint
from art import logo

print (logo)
print("Welcome to the Number Guessing Game!")
print("I'm thinking of a number between 1 and 100.")
level = input("Choose a difficulty. Type 'easy' or 'hard': ")

if level == "easy":
  life = 10
else:
  life = 5

answer = randint(1,101)

while life != 0:
  print(f"You have {life} attempts remaining to guess the number")
  guess = int(input("\nMake a guess: "))

  if guess > answer:
    print("Too high.")
    life -=1
    if life != 0:
      print("Guess again.")

  elif guess < answer:
    print("Too low.")
    life -=1
    if life != 0:
      print("Guess again.")

  elif guess == answer:
    break

if life == 0:
  print("You've run out of the guessess, you lose.")

else:
  print(f"You got it! The answer was {answer}.")

#Python #課堂筆記 #100 Days of Code







Related Posts

Day 148

Day 148

Fcitx5 一篇搞定

Fcitx5 一篇搞定

TypeScript 筆記:原始型別

TypeScript 筆記:原始型別


Comments