Day 12 – 作用域 Scope

Day 12 – 作用域 Scope

温馨提示:本文最后更新于2024-12-13 15:33:39,某些文章具有时效性,若有错误或已失效,请在下方留言

Python 没有块级作用域(Block Scope),只有局部作用域以及全局作用域

局部作用域

在函数中声明的变量(或函数)具有局部作用域(也称为函数作用域)。它们只能被同一代码块中的其他代码看到。

# 局部作用域
def drink_potion():
    potion_strength = 2
    print(potion_strength)


drink_potion()
# 不能访问作用域外的 potion_strength
# print(potion_strength)

全局作用域

在代码文件的顶层 (未缩进) 声明的变量或函数具有全局作用域。它可以在代码文件中的任何位置访问。

# 全局作用域
player_health = 10

def game():
    def drink_potion():
        player_health = 2
        print(player_health)

    drink_potion() # 2

print(player_health) # 10

修改全局变量

使用 global 关键字,可以强制代码在局部作用域内修改全局变量的值。

# 修改全局作用域
enemies = 1

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


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

# 输出
# enemies inside function: 2
# enemies outside function: 2

全局常量

全局常量一般都是使用大写,具体示例如下

PI = 3.14159
GOOGLE_URL = "https://www.google.com"

猜数字游戏

生成艺术字

ASCII Text 网站 生成所需的艺术字,如下

Guess The Number ASCII 文本

代码实现

from random import randint
from art import logo


EASY_LEVEL_TURNS = 10
HARD_LEVEL_TURNS = 5

# 检测用户猜测
def check_answer(user_guess, actual_answer, turns):
    """Checks answer against guess, returns the number of turns remaining."""
    if user_guess > actual_answer:
        print("Too high.")
        return turns - 1
    elif user_guess < actual_answer:
        print("Too low.")
        return turns - 1
    else:
        print(f"You got it! The answer was {actual_answer}")

# 设置难度级别
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)
    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()
© 版权声明
THE END
喜欢就支持一下吧
点赞0 分享
评论 抢沙发

请登录后发表评论

    暂无评论内容