#100DaysOfCode: Python Day 12

#100DaysOfCode: Python Day 12

Scope

ยท

2 min read

#100DaysOfCode Day 12

๐Ÿ”ข I CREATED MY OWN NUMBER GUESSING GAME! ๐Ÿ”ข
CLICK HERE and press "Run" to try it out.
Screenshot 2021-05-23 at 15.43.46.png

Yesterday I learned about scope. Scope is cool because it allows me to be able to write more structured code in a single file.

Lessons

  1. Once again, indentation is everything.

TO THE CODE!!!

# Scope
#############
enemies = 1

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

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

# OUTPUT
# enemies inside function: 2
# enemies outside function: 1

# Local Scope
###################
# def drink_potion():
#     potion_strength = 2
#     print(potion_strength)

# drink_potion()
# print(potion_strength)

# OUTPUT
# Error name potion_strength is not defined

# Global Scope
################
player_health = 10

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

    drink_potion()

print(player_health)

# OUTPUT
# 10

# 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)

create_enemy()

# OUTPUT
# Skeleton

# Modifying Global Scope
##########################
enemies = 1

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

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

# OUTPUT
# enemies inside function: 1
# enemies outside function: 2

#Global Constants
####################
PI = 3.14159
URL = "https://www.rishal.dev"
TWITTER_HANDLE = "@rishal92"

I have been struggling again with time management due to it being the weekend, however, I am being consistent!

Want to stay up to date with my learning journey? Just head to my home page and sign up for my newsletter.