#Scope
enemies = 1
def increase_enemies():
enemies = 2
print(f"enemies inside function: {enemies}") #enemies == 2
increase_enemies()
print(f"enemies outside function: {enemies}") #enemies === 1
#Local Scope:exists within functions
def drink_potion():
potion_strength = 2
print(potion_strength)
drink_potion()
print(potion_strength) #NameError:name potion_strength is not defined
#Global Scope
#Global variables are available within functions,no matter how deep it gets nested
#and it's also available outside of functions.
player_health = 10
def drink_potion():
potion_strength = 2
print(player_health)
drink_potion()
print(player_health)
"""This concept of global and local scope doesn't just apply to variables.
It also applies to functions and basically anything else you name.
This is a concept called the Namespace.
Anything that you give a name to has a namespace and that namespace is valid in certain scopes.
"""
#ex:
player_health = 10
def game():
def drink_potion():
potion_strength = 2
print(player_health)
drink_potion()
"""
The drink_potion now has local scope within the function game.
So now in order to call this drink_potion,I have to be within the four walls of the game function.
"""
#Block Scope
game_level = 3
def creat_enemy():
enemies = ["Skeleton","Zombie","Alien"]
if game_level < 5:
new_enemy = enemies[0]
print(new_enemy)
"""
If you create a variable within a function,then it's only available within that function.
But if yo create a variable within an if block or a while loop or a for loop
or anything that has the indentation and the colon,then that does not count as creating a separate local scope.
"""
#Modifying Global Scope
enemies = 1
def increase_enemies():
#enemies += 1
"""UnboundLocalError: local variable 'enemies' referenced before assignment
It means that the editor you're trying to tap into a local variable that
you defined somewhere around here.And then you tried to modify it by adding one to the previous value,
but you actually haven't defined it.
In order to do this,we actually have to explicitly say that we have a global variable
which is called enemies that's defined somewhere outside of this function.
"""
#Without this line of code,we cannot modify something that is global within a local scope.
global enemies
enemies += 1
print(f"enemies inside function:{enemies}")
increase_enemies()
print(f"enemies outside function:{enemies}")
"""
Modifying global scope
It's prone to creating bugs and errors,because this variable with global scope
could have been created anywhere in your code.
Don't try to modify it within a function that has local scope.
If you wanted to have this functionality like a function
that changes the number of enemies.
You could use return statements instead.
"""
def increase_enemies():
print(f"enemies inside function:{enemies}")
return enemies +1
enemies = increase_enemies()
print(f"enemies outside function:{enemies}")
#Python Constants & Global Scope
"""
In order to differentiate these constants which you're pretty much
never going to change from the variables which you are likely to change,
the naming convention in Python is to turn it into all uppercase.
"""
#ex
PI = 3.14159
URL = "https://www.google.com"
TWITTER_HANDLE = "@yu_angela"
#the Number Guessing Game
'''My way
from random import randint
answer = randint(1,100)
is_game_over = False
def guess():
guess_number = int(input("Make a guess:"))
if guess_number > answer:
print("Too high.")
elif guess_number < answer:
print("Too low.")
else:
print(f"You got it!The answer was {answer}")
is_game_over = True
def play(level):
num =0
amount = 0
if level == "easy":
amount = 10
else:
amount = 5
if num < amount:
num += 1
while not is_game_over:
guess()
if is_game_over == "True":
return answer
print("Guess again.")
print("Welcome to the Number Guessing Game!")
print("I'm thinking of a number of a number between 1 and 100.")
chosen_level = input("Choose a difficulty.Type 'easy' or 'hard':")
play(chosen_level)
'''
from random import randint
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.Return the number of turns ramianing."""
if guess > answer:
print("Too high.")
turns -= 1
elif guess < answer:
print("Too low.")
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():
#Choosing a random number between 1 and 100.
print("Welcome to the Number Guessing Game!")
print("I'm thinking of a number 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()
day12_Udemy Python 100days
最新推荐文章于 2024-08-19 14:41:29 发布